简体   繁体   中英

Optional Command line parameter Shell

lets call the following replace.sh

if "$1" !=""
then
  REPLACE_AS=$1
else
  REPLACE_AS="Tebow"
fi
find . ! -regex ".*[/]\.svn[/]?.*" -type f -print0 | xargs -0 -n 1 sed -i -e 's/SANCHEZ/'$REPLACE_AS'/g'

Sorry for the primitive question. I am trying to make it so the command line parameter is optional . IE if someone doesn't put it and just runs this script it uses Tebow. That seems to work. However if i run the script with a command line argument it doesnt work.

ie

./test.sh

this will replace it with tebow.

however ./test.sh Smith

will not replace the Sanchez string with Smith

You can use shell parameter expansion and the notation:

REPLACE_AS="${1:-Tebow}"

to do in one line what you do in 6.

Additionally, your code as written should be:

if [ "$1" != "" ]
then REPLACE_AS="$1"
else REPLACE_AS="Tebow"
fi

The test command is [ ; it needs spaces around its operands and a ] at the end. You need quotes around "$1" in case it contains spaces; the quotes around "Tebow" are optional because it doesn't contain spaces (but the uniformity is good).

There's nothing to stop you writing:

xargs -0 -n 1 sed -i -e 's/SANCHEZ/'"${1:-Tebow}"'/g'

but the clarity of the variable is good, especially if you'll refer to it several times.

Also, I would leave the pipe at the end of the line and start the second command ( xargs ) on the second line for clarity (again - it is very important).

find . ! -regex ".*[/]\.svn[/]?.*" -type f -print0 |
xargs -0 -n 1 sed -i -e 's/SANCHEZ/'"$REPLACE_AS"'/g'

Sometimes, but not often, I'll indent the second command. Note the double quotes around "$REPLACE_AS" ; it prevents problems with spaces in the replacement text.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM