1

So I got the following alias:

alias current_dir="pwd | sed -e 's/ /\\ /'"

In another place, I first safe my returned string in order to use parameter expansion to lowercase the string, like so:

CURRENT_DIR=$(current_dir)
echo "${CURRENT_DIR,,}"

But I wonder if it is possible to directly use parameter expansion on a alias/function call? I tried the following possibilities but they all didn't work for me:

echo "${current_dir,,}"       # just an empty echo
echo "${$(current_dir),,}"    # bad substitution
echo "${"$(current_dir)",,}"  # bad substitution
winklerrr
  • 13,026
  • 8
  • 71
  • 88

2 Answers2

2

No, it's not possible. You have to save the output in an intermediate variable. It's unavoidable.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
2

You could use

declare -l CURRENT_DIR=$(current_dir)

Although Shellcheck has some sage words about declare and command substitution on the same line


However, to get a properly shell-quoted/escaped version of the string, use one of

$ mkdir '/tmp/a dir "with quotes and spaces"'
$ cd !$

$ printf -v CURRENT_DIR "%q" "$PWD"
$ echo "$CURRENT_DIR"
/tmp/a\ dir\ \"with\ quotes\ and\ spaces\"

$ CURRENT_DIR=${PWD@Q}
$ echo "$CURRENT_DIR"
'/tmp/a dir "with quotes and spaces"'

Get out of the habit of using ALLCAPS variable names, leave those as reserved by the shell. One day you'll write PATH=something and then wonder why your script is broken.


${var@operator} showed up in bash 4.4:

${parameter@operator}
       Parameter transformation.  The expansion is either a transformation of the
       value of parameter or information about parameter itself, depending on the
       value of operator.  Each operator is a single letter:

       Q      The  expansion is a string that is the value of parameter quoted in
              a format that can be reused as input.
       E      The expansion is a string that is the value of parameter with back-
              slash  escape sequences expanded as with the $'...' quoting mechan-
              sim.
       P      The expansion is a string that is the result of expanding the value
              of parameter as if it were a prompt string (see PROMPTING below).
       A      The expansion is a string in the form of an assignment statement or
              declare command that, if evaluated, will  recreate  parameter  with
              its attributes and value.
       a      The  expansion  is  a string consisting of flag values representing
              parameter's attributes.

       If parameter is @ or *, the operation is applied to each positional param-
       eter in turn, and the expansion is the resultant list.  If parameter is an
       array variable subscripted with @ or *, the case modification operation is
       applied  to  each  member  of  the array in turn, and the expansion is the
       resultant list.
glenn jackman
  • 238,783
  • 38
  • 220
  • 352