1

I want to save in variable $COMMAND the second tab delimited field from variable $i, however when I do that, the command cd ~ gets executed. There is a tab character between TEST_CASE_001 and cd ~

i='TEST_CASE_001 cd ~'
COMMAND=$(echo $i | cut -f2)

How to prevent it from being executed and save it in the $COMMAND?

  • 1
    I don't think your characterisation of what's happening is accurate. Could you edit in a transcript of your experiment and the result you're seeing? – Michael Homer Apr 10 at 22:15
2

Note: this answer is for the first version of the question.

First, let's define i with the tab:

$ i=$'ls -l\tcd ~'

Now, let's try your commands without and then with double-quotes:

$ echo $i | cut -f2
ls -l cd ~
$ echo "$i" | cut -f2
cd ~

If you want cut to work as expected, you need to put $i in double-quotes. Without the double-quotes, the shell performs, among other things, word splitting which results in the tab being replaced by a blank. This prevents the cut command from working as you expect.

Doing the assignment to Command does not change this:

$ Command=$(echo $i | cut -f2); declare -p Command
declare -- Command="ls -l cd ~"
$ Command=$(echo "$i" | cut -f2); declare -p Command
declare -- Command="cd ~"

General comments

You haven't provided the larger context here but, in general, it is a bad idea to try to put commands in variables. See "I'm trying to put a command in a variable, but the complex cases always fail!".

Separately, regarding the variable COMMAND, it is better practice to use lower or mixed case for your shell variables. The system uses upper case for its variables and you don't want to accidentally overwrite one of them.

  • 1
    Thank you for your help and comments! It works now. – Alex Apr 10 at 22:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.