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
  • 589
  • 8
  • 18
  • 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) – Jason 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
  • 96,430
  • 6
  • 33
  • 74