Linux bash if in one line

One line if/else condition in linux shell scripting

I’m attempting to put this into a one line command. So far I’ve gotten it all but the else portion of the command. Here’s what I have so far.

maxline=`cat journald.conf | grep "#SystemMaxUse="` && if [ $maxline == "#SystemMaxUse mt24 mb12">
    linuxshellif-statement
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this question" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="question" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="1" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
)" title="">Improve this question
asked Aug 12, 2013 at 5:13
3
    4
    Why would you want to do such a thing, just makes your code unreadable.
    – erlc
    Aug 12, 2013 at 5:25
    3
    I'm trying to give someone a command to change their log conf file but trying to make it a c&p thing they can just run in their terminal without having to dabble with creating files and chmodding them.
    – Joshua Strot
    Aug 12, 2013 at 5:27
    11
    As for "why would anyone" use single-line if-thens. why would anyone use [ instead of test, or use | versus cat or /dev/stdin, or use mv when they could make an alias named move_file, etc.? The reason is for shorthand, in cases where you want to use it. It may be a personal choice, or it may not be. But if readability is a major concern, the command line in general is not going to be the best place for you.
    – Beejor
    Dec 23, 2018 at 1:17
Add a comment|

5 Answers 5

Reset to default
69

It looks as if you were on the right track. You just need to add the else statement after the ";" following the "then" statement. Also I would split the first line from the second line with a semicolon instead of joining it with &&.

maxline='cat journald.conf | grep "#SystemMaxUse="'; if [ $maxline == "#SystemMaxUse=" ]; then sed 's/\#SystemMaxUse=/SystemMaxUse=50M/g' journald.conf > journald.conf2 && mv journald.conf2 journald.conf; else echo "This file has been edited. You'll need to do it manually."; fi

Also in your original script, when declaring maxline you used back-ticks "`" instead of single quotes "'" which might cause problems.

Источник

One Line if-else Condition in Linux Shell Scripting

announcement - icon

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 ifelse 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 ifelse 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 ifelse 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 ifelse 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.

Источник

Single Line if. else in Bash

Single Line if. else in Bash

  1. a Multiline Example for if . else in Bash
  2. 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

Источник

Читайте также:  Palit thunder master linux
Оцените статью
Adblock
detector