2

I am trying to improve my bash knowledge as well as make my code more organized

What I am trying to do here is add the flag -u with the variable $user only if the variable exist otherwise don't mention the -u flag.

Here is what I tried to do

echo "Running: ps if [[ -n "$user"]]; then -u $user fi | wc -l" 

If $user exist is it will print the amount of proccesses $user has

however if $user does not exist just show the amount of proccesses of all users

Important to note that I need it to be this way (inside the echo)

Crapy
  • 125

1 Answers1

5

I'm not going to use echo to output variable data because it's unnecessary in this case and echo may also modify the data under some circumstances (see Why is printf better than echo?). It's also inelegant as you'd need a command substitution, and therefore it would require the shell to temporarily hold the output from ps in memory.

Instead, I would probably write the code like this to make it readable:

echo Running:
if [ -n "$user" ]; do
    ps -u "$user"
else
    ps
fi

or, if you want to start compacting it down into more unreadable chunks,

echo Running:
ps ${user:+-u "$user"}

The expansion ${variable:+word} would expand to word if the variable variable was set and not empty. Remove the : to only expand to word if the variable is set (but possibly empty). This expansion is standard, so any POSIX-like shell would support it.

If you, for whatever reason, want this on one line, then write it on one line:

echo Running:;ps ${user:+-u "$user"}

or, using the if-then-else variation,

echo Running:;if [ -n "$user" ]; do ps -u "$user"; else ps; fi
Kusalananda
  • 333,661