How can I put the output of head -15 textfile.txt to a variable $X to use it in an if command like this:

 if $X = 'disabled' then


x="$(head -15 testfile.txt)"
if [ "$x" = disabled ]
    echo "We are disabled"

Generally, any time that you want to capture the output from a command into a shell variable, use the form: variable="$(command args ...)". The variable= part is assignment. The $(...) part is command substitution.

Also note that the shell does not do if statements in the form if $X = 'disabled'. The shell expects that a command follows the if and the shell will evaluate the return code of that command. In the case above, I run the test command which can be written as either test ... or [ ... ].

Many consider it best practices to use lower-case variables for shell scripts. This is because system defined variables are upper case and you don't want to accidentally overwrite one. On the other hand, there is no system variable called X so it is not a real problem here.

| improve this answer | |

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