1

I'm trying read a file which contains lines like this:

 Run COMMAND with options "OPTIONS" and arguments "ARGUMENTS"

Then I want to execute this command with given options and arguments. For example I'd like to execute these commands:

 Run pwd with options "" and arguments ""
 Run ls with options "-al" and arguments "$HOME"
 Run ls with options "-al" and arguments "Example: \"strange folder name\""

This is my code

#!/bin/bash

while read -r line
do
 COMMAND=$(echo "$line" | cut -d" " -f 2)
 OPTIONS=$(echo "$line" | cut -d" " -f 5 | tr -d '"')
 ARGUMENTS=$(echo "$line" | cut -d" " -f 8)

 $COMMAND $OPTIONS $ARGUMENTS
 done <$1

First example is working as it should, second one is giving me error ls: cannot access $HOME: No such file or directory' and third one is not storing the name of the folder to $ARGUMENTS correctly.

2
  • 1
    Don't use cut like that. Your code is equivalent to while read -r a COMMAND b c OPTIONS d e ARGUMENTS; ... done (except that this also assigns variabls a, b, and c.) Let read parse the fields. Commented Apr 18, 2016 at 23:02
  • The suggestion from @WilliamPursell is a better way to go. To make the code even more readable and self-documenting, you can replace the unneeded variables with a variable named ignore while read -r ignore COMMAND ignore ignore OPTIONS ignore ignore ARGUMENTS; ... done. Commented Apr 19, 2016 at 1:16

1 Answer 1

1

second one is giving me error ls: cannot access $HOME: No such file or directory'

This is because the folder named $HOME does not exist. I am not talking about the value of $HOME variable, but the string literal. The shell does not execute the parameter expansion in your situation.

third one is not storing the name of the folder to $ARGUMENTS correctly

This is because -f 8 only extract column 8, try -f 8- to extract the 8th column and all the others until the end of line.

You can give a try to this version below:

while read -r line; do
  COMMAND=$(printf "%s" "${line}" | cut -d" " -f 2)
  OPTIONS=$(printf "%s" "${line}" | cut -d" " -f 5 | tr -d '"')
  ARGUMENTS=$(printf "%s" "${line}" | cut -d" " -f 8-)
  $COMMAND $OPTIONS "$(eval printf \"%s\" "$ARGUMENTS")"
done < "${1}"

The eval is a shell built-in command which is used to enable parameter expansion of ARGUMENTS, if applicable.

I have to warn you that the eval is usualy say risky to use.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.