I have simple script. Script can be run with specific arguments. For example:

./my-script.sh --last-name=Smith --first-name=John

There is called curl and sended POST-request in script:

curl --data-urlencode last_name=$lastName --data-urlencode first_name=$firstName https://example.com

Where firstName and lastName are variables, that parsed from arguments.

Issue, that firstName or lastName (but not both) can be missed. If argument is missed, appropriate parameter do not sended to server.

But I do not know, how I can implement this logic in scripts.

Ofcouse, I can add if to check argument on null, but I can have much arguments in command line and in this case I will have tons of if...


Something like this: suppose


Then in order to include only non-empty parameters, code:

command="curl "
if [ "$arg1" != "" ]; then
        command="$command --data-urlencode arg1=$arg1"
if [ "$arg2" != "" ]; then
        command="$command --data-urlencode arg2=$arg2"

echo $command

You have one if statement for each variable.

  • Thanks. curl ... $argumets works for me. – Yura Shinkarev May 22 '17 at 11:20
  • I still have only one not understanding moment. I trying send request with file. So, I'm use -F first_name=... -F last_name=... -F photo=@./file.jpg. but argument and filename can contains spaces. I can fix it from command line: -F "first_name=..." -F "last_name=..." -F "photo=@...". But I get empty arguments on server, if use variable (command): command+="-F \"first_name=...\"" (request contain parameter, but it's empty). – Yura Shinkarev May 22 '17 at 12:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.