How can I create a command line (unix/linux) instruction that uses variables to execute numerous commands?

StackOverflow https://stackoverflow.com/questions/74886

  •  09-06-2019
  •  | 
  •  

Question

I need to rearrange some content in various directories but it's a bit of a pain. In order to debug the application I'm working on (a ruby app) I need to move my gems into my gem folder one at a time (long story; nutshell: one is broken and I can't figure out which one).

So I need to do something like:

sudo mv backup/gem/foo gem/
sudo mv backup/doc/foo doc/
sudo mv backup/specification/foo.gemspec specification/

replacing "foo" each time. How can I author a simple shell script to let me do something like: gemMove("foo") and it fill in the blanks for me?

Was it helpful?

Solution

put the following into a file named gemmove:

#!/bin/bash

foo=$1

if [ x$foo == x ]; then
  echo "Must have an arg"
  exit 1
fi

for d in gem doc specification ; do 
  mv backup/$d/$1 $d
done

then do

chmod a+x gemmove

and then call 'sudo gemmove foo' to move the foo gem from the backup dirs into the real ones

OTHER TIPS

You could simply use the bash shell arguments, like this:

#!/bin/bash
# This is move.sh
mv backup/gem/$1 gem/
mv backup/doc/$1 doc/
# ...

and then execute it as:

sudo ./move.sh foo

Be sure make the script executable, with

chmod +x move.sh

in bash, something like:

function gemMove()
{
filename=$1
   mv backup/gem/$filename gem/$filename
   mv backup/doc/$filename doc/$filename
   mv backup/specification/$filename.spec specification
}

then you can just call gemMove("foo") elsewhere in the script.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top