I want to make a script that takes a file path for argument, and cds into its folder.
Here is what I made :
#!/bin/bash
#remove the file name, and change every space into \space
shorter=`echo "$1" | sed 's/\/[^\/]*$//' | sed 's/\ /\\\ /g'`
echo $shorter
cd $shorter
I actually have 2 questions (I am a relative newbie to shell scripts) :
-
How could I make the cd “persistent” ? I want to put this script into /usr/bin, and then call it from wherever in the filesystem. Upon return of the script, I want to stay in the
$shorterfolder. Basically, if pwd was /usr/bin, I could make it by typing. script /my/pathinstead of./script /my/path, but what if I am in an other folder ? -
The second question is trickier. My script fails whenever there is a space in the given argument. Although
$shorteris exactly what I want (for instance/home/jack/my\ folder/subfolder), cd fails whith the error/usr/bin/script : line 4 : cd: /home/jack/my\: no file or folder of this type. I think I have tried everything, using things likecd '$shorter'orcd "'"$shorter"'"doesn’t help. What am I missing ??
Thanks a lot for your answers
in your
.bashrcadd the following line:%means remove the smaller pattern from the end/*is the paternThen in your terminal: