I want to pass four parameters to bash script. script should copy files in user home directory.

/opt/script.sh f1 f2 f3 f4

FYI: 1-each file might be exist or not, might be one of them exist or four of them. 2- every time run script might call all or one of them like this:

/opt/script.sh f1 

/opt/script.sh f1 f4

Here is my script, it always copy f1 and seems only one of them [if] execute!

for var in "$@" ; do
    if [ $T1 = "f1" ]; then
        cp file1 /home/users
        if [ $T2 = "f2" ]; then
            cp file2 /home/users
  • 1. what is it that you are trying to do? 2. why are you looping over "$@" and then completely ignoring $var in the loop and setting T1 and T2 to $1 and $2 respectively? maybe you should be using a case statement instead. – cas Sep 14 '19 at 4:33
  • 1
    Please remember to accept answers on your previous questions. That is how you show thanks here – roaima Sep 14 '19 at 12:18
  • I know, but I don’t get appropriate answer on that question. – Mehrdad Sep 14 '19 at 15:16
  • Your comment "That’s exactly what I want, Thanks ;) – Mehrdad Aug 16 at 12:19" seems to indicate you got an appropriate answer for at least one of your questions at unix.stackexchange.com/a/535781/7696 – cas Sep 15 '19 at 1:14
  • Sorry I thought you talk about another question, link helped. :)) done. Thanks – Mehrdad Sep 15 '19 at 18:59

You should probably be using a case statement for this, rather than if/then/else.

It's unclear exactly what you are trying to do, but based on my best-guess of what that is, the following may do what you want:

for var in "$@"; do
  case "$var" in
    f1) cp file1 ~/ ;;
    f2) cp file2 ~/ ;;
    f3) cp file3 ~/ ;;
    f4) cp file4 ~/ ;;
     *) echo "Error: Unknown argument '$var'" ; exit 1 ;;

I don't see the point of it, though. cp isn't that hard to use that it needs a special wrapper script just to copy a file to your home directory. IMO it's far better to learn how to use the shell and command-line utilities than to hide the workings of even simple commands from yourself.

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.