简体   繁体   中英

How to pass argument in the custom bash function as part of a dir path?

I want to define a custom bash function, which gets an argument as a part of a dir path.

I'm new to bash scripts. The codes provided online are somehow confusing for me or don't work properly.


For example, the expected bash script looks like:

function my_copy() {
    sudo cp ~/workspace/{$1} ~/tmp/{$2} 
}

If I type my_copy ab ,

then I expect the function executes sudo cp ~/workspace/a ~/tmp/b in the terminal.


Thanks in advance.

If you have the below function in say copy.sh file and if you source it ( source copy.sh or . copy.sh ) then the function call my_copy will work as expected.

$1 and $2 are positional parameters .

ie when you call my_copy ab , $1 will have the first command line argument as its value which is a in your case and $2 which is second command line argument, will have the value b . The function will work as expected.

Also you have a logical error in the function, you have given {$1} instead of ${1} . It will expand to {a} instead of a in your function and it will throw an error that says cp: cannot stat '~/workspace/{a}': No such file or directory when you run it.

Additionally, if the number of positional parameters are greater than 10, only then it is required to use {} in between otherwise you can avoid it. eg: ${11} instead of $11 .

   function my_copy() {
        sudo cp ~/workspace/$1 ~/tmp/$2 
    }

So above function will execute the statement sudo cp ~/workspace/a ~/tmp/b as expected.

To understand the concept, you can try echo $1 , echo ${1} , echo {$1} , echo {$2} , echo ${2} and echo $2 inside the script to see the resulting values. For more special $ sign shell variables

There is a syntax error in your code. You don't call a variable like {$foo} . If 1=a and 2=b then you execute

sudo cp ~/workspace/{$1} ~/tmp/{$2}

BASH is going to replace $1 with a and $2 with b , so, BASH is going to execute

sudo cp ~/workspace/{a} ~/tmp/{b}

That means tha cp is going to fail because there is no file with a name like {a}

There is some ways to call a variable

echo $foo

echo ${foo}

echo "$foo"

echo "${foo}"

Otherwise, your code looks good, should work.

Take a look a this links first and second , it's really important to quoting your variables. If you want more information about BASH or can't sleep at night try with the Official Manual , it have everything you must know about BASH and it's a good somniferous too ;)

PS: I know $1, $2, etc are positional parameters, I called it variables because you treat it as a variable, and my anwser can be applied for both.

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