1

On Ubuntu 16.04, I have a bash script which I run as root. I want to remove all spaces from the user's input, and assign the trimmed string to a variable.

read -p "Enter username: " USERNAME
echo "$USERNAME" | sed s/' '/''/g
TRIM="$USERNAME" | sed s/' '/''/g
echo $TRIM
echo "Done"

Here's some sample input and output:

Enter username: h j k l
hjkl

Done

$TRIM is empty.
What change do I need to make to get $TRIM to contain the result?

James Newton
  • 6,203
  • 7
  • 44
  • 97

2 Answers2

5

Use $() to capture the output of a command.

trim=$(echo "$USERNAME" | sed 's/ //g')

However, you don't need a command for this, you can use the bash parameter expansion operator to do substitution.

trim=${username// /}

P.S. Don't use uppercase variable names, they're conventionally reserved for environment variables.

Barmar
  • 669,327
  • 51
  • 454
  • 560
1

There are a couple of things you should note with your script.

First of all, uppercase identifiers like USERNAME are usually reserved for environment variables. So you might well override a shell variable accidentally that causes undesired effects. Same is the case with TRIM.

Secondly, you should check the default shell in your Ubuntu distribution using the SHELL built-in. Do something like

echo $SHELL

If the output is dash or bash, you could use command substitution to achieve your objective.

trim=$(echo "$username" | sed 's/ //g')

Mind that the sed commands themselves should be put under the single quotes.

When you echo trim, use double quotes to prevent word splitting like

echo "$trim" # In your case though the double quotes doesn't make any difference
sjsam
  • 20,774
  • 4
  • 49
  • 94
  • Actually the quotes make a lot of a difference. If the user inputs an expression containing a shell wildcard character or irregular whitespace, the program without quotes will mess up the output. – tripleee Nov 24 '17 at 04:24