Running application that opens relative file path from anywhere
I have application that at startup opens file relative to executable (this file path are statically compile into program binary and I cannot modify it). I want to create an alias to it that can be run from anywhere in the system without first "cd" into it's folder to make sure file will be found.
Is that even possible ?
If the program requires you to cd
to the directory, and the program cannot be changed, you cannot run that program without cd
-ing to that directory. It is as simple as that.
You can, however, start a second shell, that cd
-s to the directory and executes the program. When the program is finished, the second shell terminates and, because your main shell did not cd
, you're still in the same place.
As a quick example:
$ alias ptmpdir="bash <<< 'cd /tmp ; pwd'"
$ ptmpdir
/tmp
This, as pointed out by Kamil Maciorowski in the comments puts the command in the STDIN of the shell. This works OK if the program does not use STDIN, like pwd
in the example, and it does not check for errors.
alias lstmpdir="bash -c 'cd /tmp && ls' ls"
checks for errors and provides the correct exit-code if the cd
fails:
$ alias ptmpdir="bash -c 'cd /hop && ls' ls"
$ if ptmpdir ; then
> echo yes
> else
> echo no
> fi
ls: line 0: cd: /hop: No such file or directory
no
If you want to pass arguments to the command as well, the alias get messy and even harder to understand. In that case. a function would be better:
$ hop(){ bash -c 'cd /tmp && exec ls "$@"' ls "$@" ; }
$ hop
7iCipjf8J7 eh._2700550 in.clean.1285563 tmp-ntt.xpi
MozillaMailnews <rest deleted>
$ hop -lrt
total 56496
drwxrwxr-x 3 ljm ljm 4096 Nov 5 17:28 gimp
drwxrwxr-x 2 ljm ljm 4096 Nov 5 18:14 jna-107183
-rw------- 1 ljm ljm 0 Nov 6 00:17 config-err-Ol5gyl
drwx------ 2 ljm ljm 4096 Nov 6 00:17 ssh-FqqWxHh4jhu8
<rest deleted>