0

In a Bash script I want to split a string into two other strings based on the last "/" it contains.

In a situation where the given string is "Example/Folder/Structure", I would like to create two other strings with the following values:

string 1 = "Example/Folder"
string 2 = "Structure"

I'm trying to create a script to get a slather coverage report for a given folder in an iOS app. Although I have minimal knowledge of Bash, I was able to get it to work when the given folder is located in the root of the project. Now I want to make the script able to handle paths so that I can get the report also for subfolders, and for that I need to differentiate the desired folder from the rest of the path.

1
  • please update the question with the code you've tried, and the (wrong) output generated by your code; consider reviewing bash parameter expansion, paying particular attention to the ## / # / %% / % pattern specifiers Commented Oct 29, 2022 at 1:01

1 Answer 1

3

basename(1), dirname(1):

path=a/b/c
basename=$(basename "$path") # c
dirname=$(dirname "$path")   # a/b

Prefix/suffix removal:

path=a/b/c
basename=${path##*/}         # c
dirname=${path%/*}           # a/b
  • Prefix/suffix removal is sufficient in some circumstances, and faster because it's native shell.
  • dirname/basename commands are slower (especially many paths in a loop etc) but handle more variable input or directory depth.
  • Eg. dirname "file" prints ., but suffix removal would print file. dirname /dir prints /, but suffix removal prints empty string; dirname also handles contiguous slashes (dirname a//b); basename a/b/ prints b, but prefix removal prints empty string.
  • If you know the structure is always 3 slashes (a/b/c), it may be safe to use prefix/suffix removal. But here I would use basename and dirname.
  • Also think about whether a better approach is to change the working directory with cd, so you can just refer to current directory with . (there's also $PWD and $OLDPWD).
Sign up to request clarification or add additional context in comments.

1 Comment

dirname=${path%"$basename"} is safer than dirname=${path%/*}

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.