- Inline if shell script
- 5 Answers 5
- update
- Single Line if. else in Bash
- a Multiline Example for if . else in Bash
- a Single Line Example for if . else in Bash
- Related Article — Bash Condition
- One Line if-else Condition in Linux Shell Scripting
- 1. Introduction
- 2. Bash One-Liners
- 3. Conditional Statements
- 4. Compacting Bash Conditional Structures
- 5. The [ Builtin
- 6. Summary
Inline if shell script
Above example is not working I get only > character not the result I’m trying to get, that is «true» When I execute ps -ef | grep -c «myApplication I get 1 output. Is it possible to create result from single line in a script ? thank you
5 Answers 5
It doesn’t work because you missed out fi to end your if statement.
counter=`ps -ef | grep -c "myApplication"`; if [ $counter -eq 1 ]; then echo "true"; fi
You can shorten it further using:
if [ $(ps -ef | grep -c "myApplication") -eq 1 ]; then echo "true"; fi
Also, do take note the issue of ps -ef | grep . matching itself as mentioned in @DigitalRoss’ answer.
update
In fact, you can do one better by using pgrep :
if [ $(pgrep -c "myApplication") -eq 1 ]; then echo "true"; fi
if pgrep myApplication 2>/dev/null; then . No need for brackets or command substitution. The bracket around the «m» isn’t needed either since pgrep doesn’t match itself unless you tell it to.
That won’t be accurate if he wants to match exactly one instance. Good point about pgrep not matching self. Updated example. Thanks.
-c for pgrep is not a valid switch at least for version 3.2.8 of procps. It’s not working in my case.
Other responses have addressed your syntax error, but I would strongly suggest you change the line to:
test $(ps -ef | grep -c myApplication) -eq 1 && echo true
If you are not trying to limit the number of occurrences to exactly 1 (eg, if you are merely trying to check for the output line myApplication and you expect it never to appear more than once) then just do:
ps -ef | grep myApplication > /dev/null && echo true
(If you need the variable counter set for later processing, neither of these solutions will be appropriate.)
Using short circuited && and || operators is often much clearer than embedding if/then constructs, especially in one-liners.
Single Line if. else in Bash
- a Multiline Example for if . else in Bash
- a Single Line Example for if . else in Bash
Conditional statements are the basic part of any program that decides to depend on various conditions. In this article, we will learn about the if . else conditional statement and how we can create a single line if . else statement.
Also, we will see necessary examples and explanations to make the topic easier.
As we know, the general syntax for the if . else in Bash is:
if [ YOUR_CONDITION_HERE ] then // Block of code when the condition matches else // Default block of code fi
Now before we go to the single-line format of an if . else statement, we need to understand the multiline format of this conditional statement.
a Multiline Example for if . else in Bash
Our example below will check whether a value is greater than 15. For this purpose, we will use an if . else statement and the multiline format.
Now, the code for our example will look like this:
num=10 if [ $num -gt 15 ] then echo "The provided value is greater than 15" else echo "The provided value is less than 15" fi
You will get the below output after you run the example code.
The provided value is less than 15
Remember the code -gt means greater than.
a Single Line Example for if . else in Bash
Now we are going to see the single-line version of the above example. This example will provide similar output, but the code structure will be a single line.
A similar code will look like the one below.
num=16 if [ $num -gt 15 ]; then echo "The value is greater than 15"; else echo "The value is less than 15"; fi
The only thing you must do here is to include a symbol ; . So from the above example, we can easily find that the general syntax for the single line if . else is something like:
if [ YOUR_CONDTION_HERE ]; then # Block of code when the condition matches; else # Default block of code; fi
You will get the below example after you run the example code.
The value is greater than 15
Writing it on a single line is very difficult when working with the nested if . else or complex conditions. And there is the highest chance of getting an error.
Besides, it will be difficult to find errors and bugs in your code if you use the single line if . else .
All the codes in this article are written in Bash. It will only be runnable in the Linux Shell environment.
Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.
Related Article — Bash Condition
One Line if-else Condition in Linux Shell Scripting
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
1. Introduction
As the ubiquitous Linux shell, Bash has its own features and scripting syntax, which upgrade those of the regular sh shell. On the other hand, most shells agree on how the basic conditional expressions work at the logical and syntactic levels.
In this tutorial, we’ll explore how to construct if–else statements on a single line. First, we look at Bash one-liners in general. Next, we do a brief refresher of conditional statements in terms of their structure and potential to stretch on multiple lines. After that, we get into compacting multi-line statements, focusing on if. Finally, we discuss a common pitfall with conditional statements.
We tested the code in this tutorial on Debian 11 (Bullseye) with GNU Bash 5.1.4. It should work in most POSIX-compliant environments.
2. Bash One-Liners
While script files are the standard, sometimes we’re after an even simpler solution to a given task. In such cases, one-liners come in very handy. A one-liner is a single line of (Bash) code that executes an atomic task we may need to be done at a given moment.
There are many advantages of single lines over their script counterparts:
- commonly adhere to the “one tool for one job” philosophy of UNIX
- generally use coding idioms, which optimize speed and size
- usually bare-bones, minimum red tape
- portability in terms of copy-paste mechanics
- easily convertible to an alias
Of course, there are disadvantages as well, especially because one-liners heavily depend on the skill of their author.
Still, there are web sites dedicated to snippets of line code dedicated to everyday tasks. For example, we can count open processes per user in one line:
$ ps hax -o user | sort | uniq -c 10 root
Here, we can keep the code on a single line with only pipes between the commands. Alternatively, we’d have to use variables, storing the data between subshell calls:
$ line1=$(ps hax -o user) $ line2=$(echo "$line1" | sort) $ line3=$(echo "$line2" | uniq -c) $ echo "$line3" 10 root
Naturally, this is not optimal. On top of this, involving more advanced shell features such as loops and conditions, we might end up with some complex syntax.
3. Conditional Statements
As we’ve already seen, basic if–else statements conform to the POSIX standard:
if COMMAND then EXPRESSIONS elif COMMAND then EXPRESSIONS else EXPRESSIONS fi
This structure is far from a single line. Moreover, we can have many lines in EXPRESSIONS. On top of that, we can expand COMMAND with the () syntax, adding still more lines. Finally, there are the && and || operators, enabling multiple COMMAND statements in each condition:
if ( ( COMMAND1 && COMMAND2 ) || COMMAND3 ) then EXPRESSIONS1 EXPRESSIONS2 fi
Actually, we can even skip the if–else structure, instead opting for the so-called ternary statement:
[ TEST_COMMAND ] && ( THEN_EXPRESSIONS ) || ( ELSE_EXPRESSIONS )
Here, based on the result of TEST_COMMAND, the script either executes the THEN_EXPRESSIONS or ELSE_EXPRESSIONS.
Obviously, there’s a lot of spacing in the above scripts, much of which may not be needed. Let’s see how we can use that to our advantage.
4. Compacting Bash Conditional Structures
In most cases, the biggest space optimizations come from knowing where we actually need newlines and where they are just cosmetic improvements.
To begin with, we can omit all whitespace around the parentheses:
if ((COMMAND1 && COMMAND2) || COMMAND3) then EXPRESSIONS1 EXPRESSIONS2 fi
In fact, we can also leave only single spaces around the && and || operators:
if ((COMMAND1 && COMMAND2) || COMMAND3) then EXPRESSIONS1 EXPRESSIONS2 fi
Critically, the shell treats then as a statement, so we can only do with a single space after it:
if ((COMMAND1 && COMMAND2) || COMMAND3) then EXPRESSIONS1 EXPRESSIONS2 fi
The final but arguably most important step is replacing all other instances of a newline with a semicolon:
if ((COMMAND1 && COMMAND2) || COMMAND3);then EXPRESSIONS1;EXPRESSIONS2;fi
The rule for this step is that semicolons are equivalent to a newline within a list of commands. Furthermore, by doing this, we lower the number of lines in multi-line EXPRESSIONS.
5. The [ Builtin
Unlike parentheses (()), which are a syntax construct, brackets denote the start and end of the [ builtin. In fact, [ is essentially the test command.
Thus, similar to other commands, whitespace is required after opening and before closing brackets:
$ if [ $(echo TEST) ]; then echo CONDITION; fi CONDITION
Let’s now try the same example without the proper spacing:
$ if [ $(echo TEST)]; then echo CONDITION; fi bash: [: missing `]' $ if [$(echo TEST) ]; then echo CONDITION; fi bash: [TEST: command not found $ if [$(echo TEST)]; then echo CONDITION; fi bash: [TEST]: command not found
As the results from our attempts show, spacing is indeed critical in some cases.
6. Summary
In this article, we discussed single-line if–else statements in contrast to their regular multi-line forms. By showing a few examples and transforming them into one-liners, we pointed out some pitfalls and considerations.
In conclusion, writing one-liners, in general, is an arguable practice unless done precisely and with attention to potential issues.