1

I have something similar in a script I'm writing:

CMD="/path/to/cmd,there.sh"
TMP="${CMD##*/}"
echo "${TMP%%,*}"

Is there a way to nest the substring removals in line 2 & 3, or produce the same result in one-line, in pure bash, without going out to another program? The length of ${CMD} is not static. To be clear, I want the output to be simply "cmd".

I've tried the below, with various forms of brackets and quotations, but get a syntax error. This is something (I think) was allowed but isn't in new versions of Bash.

echo "${${CMD##*/}%%,*}"
0

5 Answers 5

1

Unfortunately, no, it's not possible to combine or nest string operations in bash.

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

Comments

1

With bash:

[[ $CMD =~ .*/([^,]*) ]] && echo ${BASH_REMATCH[1]}

2 Comments

Was wondering if you should make the regex ^.*/([^,]*).*$ for it to be more fault-proof? Or is just enough fine? I don't see a fail-case here, anyways.
@sjsam: That would probably be possible.
0

Shell parameter substitution is primitive in that they don't provide functionalities like nesting. However, nobody prevents you from doing a sed thing here.

cmd="/path/to/cmd,there.sh" # Use lower-case identifiers for user variables
cmd=$(sed -E 's#^.*/([^,]+),.*$#\1#' <<<"$cmd")

The <<< enables the use of herestrings in bash.

Comments

0

I've found that zsh actually supports nested string operations, so I actually switched the interpreter to zsh for my script and the below works fine:

echo "${${CMD##*/}%%,*}"

Comments

0

If you want to write the script "in one line", just use ; or && to indicate the end of a line instead of a line-break:

CMD="/path/to/cmd,there.sh"; TMP="${CMD##*/}"; echo "${TMP%%,*}"

or

CMD="/path/to/cmd,there.sh" && TMP="${CMD##*/}" && echo "${TMP%%,*}"

A more elaborate answer about combining commands can be found below this question.

Disclaimer: I understand that it is debatable whether or not this is a one-liner. But if you are visiting this question looking for a way to throw this in bash, it may answer your question regardless.

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.