1748112 Members
3441 Online
108758 Solutions
New Discussion юеВ

Re: variable in if

 
SOLVED
Go to solution
Gemini_2
Regular Advisor

variable in if

I would like to change the following two statements into one.

"list=$(ls -1 $xturns/tur*)
if [ "$list" ];then"

how can I do that?

i tried
if [ $list=$(ls -1 $xturns/tur*) ]; then

but...it doesnt work...

for shell script..please advise
14 REPLIES 14
James R. Ferguson
Acclaimed Contributor

Re: variable in if

Hi Gemini:

# LIST=$(ls -1 /tmp/tur* 2>/dev/null||echo "empty")

# echo ${LIST}

...would return a list of files or the word "empty"

Is that your objective?

Regards!

...JRF...
Gemini_2
Regular Advisor

Re: variable in if

not quite.

I just want to condense two statements into one in the if statement. can that be done?

James R. Ferguson
Acclaimed Contributor

Re: variable in if

Hi:

Again, I'm not sure of your objective, but:

if [ -z "$(ls -1 /tmp/gemini* 2>/dev/null)" ]; then
echo "empty"
else
echo "ok"
fi

...Note that no variable is necessary for capturing the list.

Regards!

...JRF...
Gemini_2
Regular Advisor

Re: variable in if

ah, you are right.. I didnt make myself clear. I left one important part. my bad.

use your example

if [ -z "$(ls -1 /tmp/gemini* 2>/dev/null)" ]; then
echo "empty"
else
echo "ok"
fi

what if i want to echo the result of ls -l? then what do you do

thanks for your patience





James R. Ferguson
Acclaimed Contributor

Re: variable in if

Hi (again):

I think the best we might do is:

# LIST=$(ls -1 /tmp/gemini* 2>/dev/null)
# [ -z "${LIST}" ] && echo "empty" || echo ${LIST}

...yes, that's two statements, but ...

Regards!

...JRF...
Gemini_2
Regular Advisor

Re: variable in if

I was hoping to have something like this

[ -z "${LIST}=$(ls -1 /tmp/gemini* 2>/dev/null)" ] && echo "empty" || echo ${LIST}


but, i know my syntax is not quite right...


anyway..thaks for your help..
Steven Schweda
Honored Contributor

Re: variable in if

Just so I understand, ...

You have two simple statements which work
properly, and are easy to understand, and you
wish to combine them into a single, more
complex statement because you think that that
will look better somehow?

Is that the goal here?
Gemini_2
Regular Advisor

Re: variable in if

I know

I just thought that option is available...but I forgot it...I just want to know it for memory refresh purple

but, thanks for your help anyway
Dennis Handly
Acclaimed Contributor
Solution

Re: variable in if

>I would like to change the following two statements into one.

You would do the obvious:
if [ "$(ls -1 $xturns/tur*)" ]; then

Compare to JRF's solution where -z tests for empty string.

>what if I want to echo the result of ls -l?

As Steven said, why make it harder to understand?

But if you insist, if may be something like:
[ -z "${LIST:=$(ls -1 /tmp/gemini* 2>/dev/null)}" ] && echo "empty" || echo ${LIST}

Note: You would really need to unset LIST to make sure it gets set.