0

I am currently saving string outputs from expressions like so

SOME_PATH="/some/path/file"
FILE_NAME=`echo "$SOME_PATH" | rev | cut -f 1 -d "/" | rev )`
FILE_FOLDER=`echo "$SOME_PATH" | sed s/$FILE_NAME//`

echo ${SOME_PATH}
echo ${FILE_NAME}
echo ${FILE_FOLDER}

which seems like the echo is superfluous, but I couldn't get it to work without it. What is the preferred way?

neolith
  • 699
  • 1
  • 11
  • 20
  • 1
    I suggest a [here string](https://en.wikipedia.org/wiki/Here_document#Here_strings). – Cyrus Oct 14 '21 at 11:14
  • 2
    So you want the `basename` and the `dirname`? These commands do exactly this: `basename /some/path/file --> file`, and `dirname /some/path/file --> /some/path`. – Renaud Pacalet Oct 14 '21 at 11:15
  • you could use basename and dirname to simplify this also $( xxyyy ) should be used in preference to backticks (which is inherited from sh) – Jay M Oct 14 '21 at 11:19

1 Answers1

1

What is the preferred way?

The preferred way is to use variable expansions.

somepath='/some/path'
filename=${somepath##*/}
dirname=${somepath%/*}

Also: do not use backticks `, prefer $(...), quote variable expansions "s/$FILE_NAME//", prefer to use lower case variables for local variables and check your scripts with shellcheck.

How to assign string outputs of expressions in variables without echo?

Use here string to save one fork() call.

var=$(<<<"$var" command)
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • ``FILE_NAME=$(<<<"$SOME_PATH" | rev | cut -f 1 -d "/" | rev )`` doesn't work – neolith Oct 14 '21 at 11:23
  • It works for the basename and dirname commands from Renaud Pacalet though. Can you explain why the variable expansions are better? – neolith Oct 14 '21 at 11:30
  • `<<<"$SOME_PATH" | rev` not `<<<"$var" | command` but `<<<"$var" command`. `<<<"$var"` is not a command, it does nothing, `|` pipeing it does nothing. `why the variable expansions are better?` Because they do not spawn external processes. – KamilCuk Oct 14 '21 at 11:52