Adam
Adam

Reputation: 138

What is the equivalent of %%~nxD in Bash?

I'm working on converting some batch scripts into a bash script to build a project on Linux and I need to convert %%~nxD to Bash. It is used in the following form:

FOR %%D IN ("%SOURCE_DIR%\..\..") DO SET "ProjName=%%~nxD"

If anyone could shed some light on this it would be much appreciated.

Upvotes: 1

Views: 1342

Answers (2)

Dummy00001
Dummy00001

Reputation: 17420

FOR %%D IN ("%SOURCE_DIR%\..\..") DO SET "ProjName=%%~nxD"

(Assuming that is to find the third path component of the SOURCE_DIR variable.)

In bash, that might look like this:

ProjName=$(basename `(cd $SOURCE_DIR/../..; pwd)`)

(cd - change into the directory, pwd - print the current directory, basename - take the last component of the name.)

Alternatively:

ProjName=$(basename $(dirname $(dirname $SOURCE_DIR)))

(Strip two path components with the dirname, then take the last component with the basename.)

or, without extra commands (fast, but ugly):

TEMP1=${SOURCE_DIR%/*/*}
ProjName=${TEMP1##*/}

(The same as previous, but using the bash' built-in string expansion. Search man bash for ## - it would lead you directly to the string expansion description.)

The major differences between the options are:

  • The first is ugly, but IME the most reliable, and thanks to the pwd can be used to resolve the symlinks. (Also allows for error checking.)
  • The second simulates the ../.. with nested dirname calls.
  • The third does the same as second, but is faster since it doesn't use the commands, but string expansion instead. But it has a flaw that if $SOURCE_DIR ends with a redundant /, it might not work as expected.

Upvotes: 3

SaintHax
SaintHax

Reputation: 1943

Guessing since you didn't add what it does in DOS that you want the parent directory?

var=${PWD%*/}

if it's the current directory, no path

var=${PWD##/*}

Upvotes: 0

Related Questions