Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

concatenate inputs in bash script [duplicate]

I would like to concatenate all the arguments passed to my bash script except the flag.

So for example, If the script takes inputs as follows:

./myBashScript.sh -flag1 exampleString1 exampleString2

I want the result to be "exampleString1_exampleString2"

I can do this for a predefined number of inputs (i.e. 2), but how can i do it for an arbitrary number of inputs?

like image 224
zpesk Avatar asked Feb 20 '12 00:02

zpesk


People also ask

How do you concatenate variables in Bash?

The += Operator in Bash Bash is a widely used shell in Linux, and it supports the '+=' operator to concatenate two variables. As the example above shows, in Bash, we can easily use the += operator to concatenate string variables.

How do you assign a all the arguments to a single variable?

Assigning the arguments to a regular variable (as in args="$@" ) mashes all the arguments together like "$*" does. If you want to store the arguments in a variable, use an array with args=("$@") (the parentheses make it an array), and then reference them as e.g. "${args[0]}" etc.

What is || in scripting?

4. OR Operator (||) The OR Operator (||) is much like an 'else' statement in programming. The above operator allow you to execute second command only if the execution of first command fails, i.e., the exit status of first command is '1'.


1 Answers

function concatenate_args
{
    string=""
    for a in "$@" # Loop over arguments
    do
        if [[ "${a:0:1}" != "-" ]] # Ignore flags (first character is -)
        then
            if [[ "$string" != "" ]]
            then
                string+="_" # Delimeter
            fi
            string+="$a"
        fi
    done
    echo "$string"
}

# Usage:
args="$(concatenate_args "$@")"
like image 54
Tyilo Avatar answered Oct 04 '22 00:10

Tyilo