0

I want to extract the output of a command run through shell script in a variable but I am not able to do it. I am using grep command for the same. Please help me in getting the desired output in a variable.

x=$(pwd)
pw=$(grep '\(.*\)/bin' $x)
echo "extracted is:"
echo $pw

The output of the pwd command is /opt/abc/bin/ and I want only /root/abc part of it. Thanks in advance.

4 Answers 4

1

Use dirname to get the path and not the last segment of the path.

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

2 Comments

I have made a modification, the last part bin is not a file but a directory so there is an error saying /opt/abc/bin: is a directory.
The error you are seeing is from the grep command which you are using incorrectly. grep expects a file not a directory.
1

You can use:

x=$(pwd)
pw=`dirname $x`
echo $pw

Or simply:

pw=`dirname $(pwd)`
echo $pw

1 Comment

The lack of proper quoting should also be fixed; echo "$pw".
1

All of what you're doing can be done in a single echo:

echo "${PWD%/*}"

$PWD variable represents current directory and %/* removes last / and part after last /.

For your case it will output: /root/abc

Comments

0

The second (and any subsequent) argument to grep is the name of a file to search, not a string to perform matching against.

Furthermore, grep prints the matching line or (with -o) the matching string, not whatever the parentheses captured. For that, you want a different tool.

Minimally fixing your code would be

x=$(pwd)
pw=$(printf '%s\n' "$x" | sed 's%\(.*\)/bin.*%\1%')

(If you only care about Bash, not other shells, you could do sed ... <<<"$x" without the explicit pipe; the syntax is also somewhat more satisfying.)

But of course, the shell has basic string manipulation functions built in.

pw=${x%/bin*}

Comments

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.