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

Answers


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.


Need Your Help

Makefile: run bash script via 'make all' command BEFORE global variables initialization

c++ bash makefile

Is it possible to execute bash script through command 'make all' before variable initialization. The idea is that this script compiles idls and creates new directories in whitch puts .h and .cpp fi...

ACR122U Sending Direct commands returning -2 and Segmentation fault

c centos apdu acr122 lib-nfc

I am trying to send a direct command to the ACR122U reader.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.