12

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?

2 Answers 2

20

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 && "$@"
2
  • Thank you Charles ....am I right in making the last line above to be "$cmd" "$@" to make the "arguments" optional to the command i.e. if I run "./changedir /etc/ ls" it will work ok and also " ./indir /etc/ ls -al" will also work ok
    – frodo
    Commented Dec 3, 2011 at 17:41
  • @frodo: Yes, you are right. "$@" is better because it preserves arguments as they are passed. It's what I meant but not what I wrote!
    – CB Bailey
    Commented Dec 3, 2011 at 18:24
-1

Since there can probably be more than a single argument to a command, i would recommend using quotation marks. Something like this:

sh changedir.sh /etc "ls -lsah"

Your code would be much more readable if you ommited the 'shift':

directory=$1;
command=$2;
cd $directory
$command

or simply

cd DIRECTORY_HERE; COMMAND_WITH_ARGS_HERE
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.