Search code examples
stringbashzshpbscommand-substitution

Command substitution as a variable in one-liner


I get the following error:

> echo "${$(qstat -a | grep kig):0:7}"
-bash: ${$(qstat -a | grep kig):0:7}: bad substitution

I'm trying to take the number before. of

> qstat -a | grep kig
1192530.perceus-     kigumen     lr_regul pbs.sh            27198     2     16    --  24:00:00 R 00:32:23

and use it as an argument to qdel in openPBS so that I can delete all process that I started with my login kigumen

so ideally, this should work:

qdel ${$(qstat -a | grep kig):0:7}

so far, only this works:

str=$(qstat -a | grep kig); qdel "${str:0:7}"

but I want a clean one-liner without a temporary variable.


Solution

  • The shell substring construct you're using (:0:7) only works on variables, not command substitution. If you want to do this in a single operation, you'll need to trim the string as part of the pipeline, something like one of these:

    echo "$(qstat -a | grep kig | sed 's/[.].*//')"
    echo "$(qstat -a | awk -F. '/kig/ {print $1}')"
    echo "$(qstat -a | awk '/kig/ {print substr($0, 1, 7)}')"
    

    (Note that the first two print everything before the first ".", while the last prints the first 7 characters.) I don't know that any of them are particularly cleaner, but they do it without a temp variable...