0

MY code:

$test =$(ps -ef |grep -c "java")

echo "$test"

it's giving me error:

root@test:~# ./restart.sh

./restart.sh: line 1: =4: command not found

There 4 java process running.

2 Answers 2

3

Try:

test=$(ps -ef |grep -c "java")
echo "$test"

I think you just need to remove the first $ sign.

To assign output of any shell command to variable in bash, use the following command substitution syntax:

var=$(command-name-here)
var=$(command-name-here arg1)
var=$(/path/to/command)
var=$(/path/to/command arg1 arg2)

Edit: "Do not put any spaces before or after the equals sign"

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

3 Comments

The other critical correction here is to remove the spaces around =
I added "Do not put any spaces after the equals sign" to my reason for editing the post shortly after answering (removing the space from the solution), having realised just that. I'm new to SO, so unsure if that shows up anywhere. Up voted your comment as it's relevant.
Thank you for the heads up.
0

the correct code is

test =$(ps -ef |grep -c "java")

echo "$test"

doing $test will take the value of the variable test, which is empty at start, thus you code will be equivalent to

=$(ps -ef |grep -c "java")

evaluated at =4 (I suppose you have 4 java-named processes running)

which causes your error

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.