Chunde  Huang
Chunde Huang

Reputation: 385

linux bash, passing paramenters using a varible issue

I am trying to use a variable to store the parameters, here is the simple test:

#!/bin/bash
sed_args="-e \"s/aaaa/bbbb/g\""
echo $sed_args`

I expected the output to be

-e "s/aaaa/bbbb/g"

but it gives:

"s/aaaa/bbbb/g"

without the "-e"

I am new to bash, any comment is welcome. Thanks, maybe this is already answered somewhere.

Upvotes: 1

Views: 51

Answers (2)

Léa Gris
Léa Gris

Reputation: 19545

You need an array to construct arguments dynamically:

#!/usr/bin/env bash

sed_args=('-e' 's/aaaa/bbbb/g')
echo "${sed_args[@]}"

Upvotes: 2

choroba
choroba

Reputation: 241768

When you use the variable without double quotes, it gets word split by the shell even before echo sees the value(s). Then, the bash's builtin echo interprets -e as a parameter for itself (which is normally used to turn on interpretation of backslash escapes).

When you double quote the variable, it won't be split and will be interpreted as a single argument to echo:

echo "$sed_args"

For strings you don't control, it's safer to use printf as it doesn't take any arguments after the format string:

printf %s "$string"

Upvotes: 1

Related Questions