frodo
frodo

Reputation: 1063

bash script to change directory and execute command with arguments

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?

Upvotes: 12

Views: 48933

Answers (2)

CB Bailey
CB Bailey

Reputation: 791401

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 && "$@"

Upvotes: 20

dgasper
dgasper

Reputation: 212

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

Upvotes: -1

Related Questions