Change directory and execute file in one command
Asked Answered
N

3

38

When I want to execute a file, it seems that I always have to first 'cd' into that file's directory before executing it, unless it fails on a can't-find-my-dataz type error.

How can I get around typing two commands to just execute a program?

Example:

cd /usr/local/bin/minecraft/
java -Xms512M -Xmx2048M -jar minecraft.jar

How can I make that into one line, so as I can put it as my Exec=_ line when creating a custom launcher in Gnome3?

Necrophilia answered 29/11, 2012 at 10:50 Comment(0)
C
90

cd /usr/local/bin/minecraft/ && java -Xms512M -Xmx2048M -jar minecraft.jar should do it

Coprology answered 29/11, 2012 at 10:54 Comment(2)
+1: The advantage of this command is that the cd fails, the java-command won't even be executedOligoclase
I am doing the same using Python os.system("start /B start cmd.exe @cmd /k cd <my directory path> && <my second command>") but the second command ends up being executing before my Change Directory command, hence fails, any workaround for this? ThanksAutointoxication
D
13

I am answering this question again with some extension so that others may find this useful.

cd /usr/local/bin/minecraft/ && java -Xms512M -Xmx2048M -jar minecraft.jar

This command will do for sure. But after running this command, you will stay in /usr/local/bin/minecraft/ directory. And, if you are using this command in a bash script, all the later commands will be executed in this directory.

If you want to run the command in your desired directory and get immediately back to where you were, enclose the command with parenthesis, i.e.,

(cd /usr/local/bin/minecraft/ && java -Xms512M -Xmx2048M -jar minecraft.jar)
Daryn answered 11/11, 2020 at 14:57 Comment(0)
P
0

Alternatively (e.g. if passing somewhere else to be executed)

    sh -c 'cd /usr/local/bin/minecraft; exec java -Xms512M -Xmx2048M -jar minecraft.jar'
Photic answered 28/6, 2022 at 1:49 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.