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.

2
  • 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. Commented Oct 8, 2015 at 6:30
  • The error you are seeing is from the grep command which you are using incorrectly. grep expects a file not a directory.
    – sashang
    Commented Oct 8, 2015 at 6:34
1

You can use:

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

Or simply:

pw=`dirname $(pwd)`
echo $pw
1
  • The lack of proper quoting should also be fixed; echo "$pw".
    – tripleee
    Commented Oct 8, 2015 at 6:34
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

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*}

Not the answer you're looking for? Browse other questions tagged or ask your own question.