0

I am writing a script and I noticed that a certain line of code is constantly being reused.

So I thought why not put it into a variable for ease of use, and when something changes, I only need to change it in one location.

When I do this:

scriptpath="echo -e "\n" && curl -s -u lalala:hihihi ftp://ftp.somewhere.com/folder"

and then use the variable as following:

$SCRIPTPATH/some_script.sh | bash

I get the following error message:

bash: line 2: $'\n': command not found

10
  • 3
    Is there a reason you don't just create a function to do the commands, storing commands in variables is generally bad practice. Dec 20 '18 at 13:19
  • the $SCRIPTPATH is part of a larger command, so i dont know how to combine functions and commands in one line together
    – WingZero
    Dec 20 '18 at 13:23
  • or is it possible to call forth a function with a variable?
    – WingZero
    Dec 20 '18 at 13:24
  • 4
    Perhaps you could give a more full picture of what you're actually trying to do, it feels like we might have something of an XY problem. Dec 20 '18 at 13:31
  • 1
    You can pass arguments to functions, does that solve the problem there? Dec 20 '18 at 13:32
1

You're describing a situation in which a function is exactly what you want.

do_download () {
    printf '\n'
    curl -s -u lalala:hihihi ftp://ftp.somewhere.com/folder
}

You would then use this in your code as

do_download

If the function needs to take an argument, for example the URL to use,

do_download () {
    printf '\n'
    curl -s -u lalala:hihihi "$1"
}

Then call it as

do_download "ftp://ftp.somewhere.com/folder"

Storing commands in variables is very rarely something that you'd want to do as quoting and word splitting is difficult to get right. See e.g. "How can we run a command stored in a variable?".

This site is temporarily in read only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .