Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash script to change directory and execute command with arguments

Tags:

bash

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?

like image 575
frodo Avatar asked Dec 03 '11 17:12

frodo


People also ask

How do I change directory in bash script?

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.

How do I run a shell script from a different directory?

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'.

Can Bash scripts take arguments?

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.


1 Answers

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 && "$@"
like image 168
CB Bailey Avatar answered Oct 18 '22 13:10

CB Bailey