1

I am trying to truncate a string in bash, specifically to get into the directory of an executable linked by a symlink. For example:

[alva@brnzn ~ $] ls -algh $(which python3.4)
lrwxr-xr-x  1 admin    73B 26 May 02:49 /opt/local/bin/python3.4 -> /opt/local/Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4

So i cut out the fields I don't need:

[alva@brnzn ~ $] ls -algh $(which python3.4) | cut -d" " -f 14
/opt/local/Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4

I need help to cut out everything after the last /. I am interested in a solution were I can save the previous string in a var and using variable expansion to cut out the part of the string I dont need. e.g. printf '%s\n' "${path_str#*/}" (this is just an example).

Thank you!

3
  • Why can't you save the previous string in a variable? path_str=$(command) saves the output of a command in a variable. Commented Aug 27, 2015 at 9:54
  • Indeed I would do so, but the point of the question is not how to save a string in a variable, but how to truncate part of it. Thank you. Commented Aug 27, 2015 at 10:23
  • Sorry, it looked like you already knew how to use expansion operators to truncate part of it. Commented Aug 27, 2015 at 10:24

2 Answers 2

3

You can use dirname to retrieve the final directory-name and than assign it to a variable, so the solution could be:

MY_VAR=$( dirname $(ls -algh $(which python3.4) | cut -d" " -f 14) )

But I prefer to use readlink to show the linked file so your code should be:

MY_VAR=$( dirname $( readlink $(which python3.4) )

Take a look to How to resolve symbolic links in a shell script to read the full history.

Sign up to request clarification or add additional context in comments.

Comments

1

Would this be what you need?

$ x=/opt/local/Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4
$ echo ${x%/*}
/opt/local/Library/Frameworks/Python.framework/Versions/3.4/bin

3 Comments

Thank you very much, this is exactly what I was looking for. May you point me to the documentation of the syntax you have used?
@alva It's documented in the bash manual, in the section on parameter expansion.

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.