Assign expression to a variable

This code strips out any []. It works great

echo "127[.]0[.]0[.]1" | tr -d "[]"

I would like to do the same thing but with shell scripting. User would enter:

./test 127[.]0[.]0[.]1

Output should be: 127.0.0.1
I would like to assign it to a different variable. I have something like this but I get a syntax error and I'm not sure why.

#!/bin/bash
a=$1 | tr -d "[]"
echo $a

This works just fine:

echo $1 | tr -d "[]"

But I would like to assign it to a variable and I don't know how.

Hello Loc,

Could you please try following and let me know if this helps you.

cat script.ksh
VAR=$(echo $1 | tr -d "[]")
echo $VAR

So following will be output while running it.

./script.ksh 127[.]0[.]0[.]1
127.0.0.1

Thanks,
R. Singh

I thought it would display the output twice because you used echo twice but it's not the case. This works great. thank you

That's what the $( ... ) brackets do, they capture output so you can assign it to something.

How about pure shell (Parameter Expansion : Pattern substitution):

echo $1, ${1//[][]}
127[.]0[.]0[.]1, 127.0.0.1
1 Like

I guess you mean

./script.ksh '127[.]0[.]0[.]1'

instead of

./script.ksh 127[.]0[.]0[.]1

because without the quotes, your script would not see the brackets.

Hi rovf,
If, and only if, there is a file named 127.0.0.1 in the directory in which you invoke the command:

./script.ksh 127[.]0[.]0[.]1

then the shell would start script.ksh with $1 set to 127.0.0.1 . Otherwise, the shell would start script.ksh with $1 set to 127[.]0[.]0[.]1 .

With the specific code suggested in this thread in posts #2 and #5, the output produced would be identical if the input operand is single-quoted, double-quoted, backslash-escaped, or unquoted.

1 Like

You are right! I was too much stuck into zsh (where you would get an error "no matches found", unless you explicitly override this), and did not remember that bash and ksh are different in this respect.

Ronald