0

I tried check shell script condition for same as javascript but is this not working

javascript

const data = "string";
if (data) {
   console.log("condition true");
}

shell script

# /bin/bash

data="string"
name=test
age=24

if($data); then
echo "condition satisfied"
fi

if [ "$data" && "$name" && "$age" ]; then
    echo "condition satisfied"
fi

check here

0

2 Answers 2

1

Use the test command, usually written as [.

#!/bin/bash

data="string"
if [ -n "$data" ]; then
    echo "condition satisfied"
fi

For multiple conditions use && between the tests.

if [ -n "$data" ] && [ -n "$name" ] && [ -n "$age" ]
Sign up to request clarification or add additional context in comments.

6 Comments

Note that if the string is literally just the word string, you don't need the double quotes; you only need those if the value has spaces or certain other special characters in it (in which case single quotes would be safer). Since you tagged this bash, note that you can also remove the double quotes around $data if you use double [[...]]instead of single [...]. That doesn't work in all sh-compatible shells and is not part of the POSIX spec for such, though.
Thanks barmar, but I have another doubt is how check multiple condition in single condition help for us
The literal assignment is presumably just an example, in a real application the variable would be set dynamically. And I prefer to quote variables all the time, it's easier than trying to remember when they can be omitted. @MarkReed
@SaranRaj I think you need to learn shell scripting, this isn't a programming school.
Yes barmar I am beginner for this.
|
0

Assuming that you want to see the equivalent to console log printed to stdout, the following will do:

[ "$data" ] && echo "condition satisfied"

or equivalently

test "$data" && echo "condition satisfied"

(the double quotes are needed for the case data contains a space), or, provided you have bash (since you tagged the question for bash and for shell),

[[ $data ]] && echo "condition satisfied"

Here the quotes are not needed.

All variants test whether the variable data contains a non-empty string, and if this is the case, it prints the message.

This is of course not exactly the same as if(data) in JavaScript, because in JavaScript, if data had the value 0, the condition would be considered false. You can emulate this behvaviour in shell too, but it gets more cumbersome.

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.