I am trying to do the following task:
write a shell script called changedir
which
takes a directory name, a command name and (optionally) some additional arguments.
The script will then change into the directory indicated, and
executes the command indicated with the arguments provided.
Here an example:
$ sh changedir /etc ls -al
This should change into the /etc
directory and run the command ls -al
.
So far I have:
#!/bin/sh
directory=$1; shift
command=$1; shift
args=$1; shift
cd $directory
$command
If I run the above like sh changedir /etc ls
it changes and lists the directory. But if I add arguments to the ls
it does not work. What do I need to do to correct it?
To change directories, use the command cd followed by the name of the directory (e.g. cd downloads ). Then, you can print your current working directory again to check the new path.
To use full path you type sh /home/user/scripts/someScript . sh /path/to/file is different from /path/to/file . sh runs /bin/sh which is symlinked to /bin/dash . Just making something clear on the examples you see on the net, normally you see sh ./somescript which can also be typed as `sh /path/to/script/scriptitself'.
A command line argument is a parameter that we can supply to our Bash script at execution. They allow a user to dynamically affect the actions your script will perform or the output it will generate.
You seemed to be ignoring the remainder of the arguments to your command.
If I understand correctly you need to do something like this:
#!/bin/sh
cd "$1" # change to directory specified by arg 1
shift # drop arg 1
cmd="$1" # grab command from next argument
shift # drop next argument
"$cmd" "$@" # expand remaining arguments, retaining original word separations
A simpler and safer variant would be:
#!/bin/sh
cd "$1" && shift && "$@"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With