Questions tagged [control-flow]
Control flow refers to the order that computer code is executed in when a program or script is running. Examples include loops (code is repeated) and conditionals where one branch is run instead of another. Use this tag for questions about control flow in scripts or programs – not questions about terminal flow control.
83 questions
10
votes
4
answers
943
views
With `#!/bin/sh`, what is the closest to `;;&` (`bash`'s fallthrough)?
Without ;;&, /bin/sh gives Syntax error: ")" unexpected (expecting ";;").
;;& triggers shellcheck's ^-- SC2127 (error): To use cases with ;;&, specify #!/usr/bin/env ...
1
vote
3
answers
355
views
How to tail continuously a log file that is being deleted and recreated?
I need to extract information from a log file that is deleted and recreated every time a program runs. After detecting that the file exists (again), I would like to tail it for a certain regexp.
The ...
0
votes
1
answer
156
views
Is a newline equivalent to && in a bash script?
I'm very simply wondering if, in a bash script,
a new line is functionally 100% equivalent to &&?
e.g.:
#!/bin/bash
7z x "${file}"
mv "${file}" "${new_file}"
...
2
votes
4
answers
167
views
How to execute a command after the previous non-terminating command prints a certain string?
I want to execute commandA which prints the following:
line1
line2
line3
started successfully
line4
...
...
And when the line started successfully is printed I want to start another command (and ...
5
votes
3
answers
985
views
Tool to detect errors in application's execution logic
I want to detect errors in application's execution logic. E.g.:
forgot to call free() on address returned by malloc()
did not close file handle returned by open()
invalid flags passed to open()
...
0
votes
0
answers
29
views
How do I get this code to evaluate all arms of if-else? Why does Bash seem to interpret the characters that I input as integers? [duplicate]
The last elif arm does not get executed:
#!/usr/bin/bash
searches=("feet"
"axilas"
"lactant")
length=${#searches[@]}
searchFunction() {
echo "Enter the respective ...
0
votes
0
answers
15
views
my if statement is returning command not found [duplicate]
in my script
an if statement
returns:
line 3: []: command not found
the statement:
if ["$(pidof -x $(basename $0) -o %PPID)"]; then
echo process already running; exit;
fi
what I tried:
...
6
votes
1
answer
8k
views
if ! <command> (...) vs. <command> ; if [ $? -eq 0 ] (...)
I am working on a shell script and decided to check my work via shellcheck.net. I am able to get functionally the same behavior of the following two lines in my script:
findmnt /dev/sda1 >/dev/null ...
2
votes
1
answer
427
views
Executing a remote script from a code repository causes endless loop
I often execute raw versions of remote Bash scripts in GitHub with this pattern:
wget -O - https://raw.githubusercontent.com/<username>/<project>/<branch>/<path>/<file> | ...
0
votes
1
answer
45
views
Pausing script execution until user quits out of `less`
Goal: less the contents (from a variable) and then ask the user whether the contents should be saved to a file (i.e., .recovered_object) only after the user quits out of less.
The excerpt from my ...
0
votes
2
answers
342
views
How to modify and write to file before printing to STDERR
I am working on an automated pull request check via GitHub actions and I want to preserve some data from a command's stderr output between jobs.
For this, I need to write the stderr to an artifact ...
3
votes
5
answers
3k
views
How to achieve an early exit from a code block in a bash script (analogous to perl's `last` directive)?
One feature of Perl that I really like is its generalization of looping control keywords to any curly-brace-delimited lexical block1.
For example, one can use Perl's last directive to exit any such ...
4
votes
2
answers
5k
views
Return "continue" from function called from loop
I'm currently refactoring a script which has slowly grown beyond control. I'm trying to spin off repetition into functions. However, I have a repeated test being called from a loop, and want it to ...
3
votes
2
answers
15k
views
what is the use of script 2>/dev/null in the following script? [duplicate]
$!/bin/sh
if grep "$1" /etc/passwd 2>/dev/null #Search username at beging of line1
then
echo "Pattern found - Job Over"
else
echo "Pattern not found"
fi
7
votes
2
answers
1k
views
How to know the code flow of a driver module?
I am studying Linux device drivers, my main focus is on wifi drivers.
I want to know how the code flows when I plugin my device.
Maybe, I can do something like add a printk line in every function.
...
2
votes
1
answer
2k
views
Zsh: timeout for vared builtin
I've got a while loop that uses vared to prompt for user input. I am looking for a way to have it timeout, execute a default variable and loop back to the prompt if there is not user input after a ...
0
votes
2
answers
2k
views
How to count the number of lines in the middle of a pipe
I want to count the number of lines in a pipe and then continue the pipe depending on the outcome.
I tried
x=$(printf 'faa\nbor\nbaz\n' \
| tee /dev/stderr | wc -l) 2>&1 \
| if [[ $x -ge ...
3
votes
2
answers
331
views
Is it possible to use && operator in terminal command template loop?
I wanted to make a list of similar clear commands clearer to read, so I've made a little terminal loop
for what in \
cache \
thumbs \
; do my template $what:clear; done
It works great, however ...
1
vote
3
answers
2k
views
Bash - run one script when previous is sucessful else run another script?
I think my question is similar to this one but with one extrat step - say I have 3 scripts:
main_script.sh
report_success.sh
report_failure.sh
How can I do something like this pseudo-code does:
if (...
7
votes
1
answer
2k
views
Running script line by line automatically yet being asked before each line from second line onwards
I work on a script of about 20 lines which I find myself testing time and again by copy-pasting and executing line by line.
Instead of copying-pasting each line and hitting Enter to execute, I would ...
67
votes
5
answers
80k
views
What is "declare" in Bash?
After reading ilkkachu's answer to this question I learned on the existence of the declare (with argument -n) shell built in.
help declare brings:
Set variable values and attributes.
Declare ...
-1
votes
2
answers
1k
views
The need for $1 and $2 for comparison with an here-string
This is a follow up to this question;
I don't know why but I keep misunderstanding the following code, although I try very hard to understand it:
function read_and_verify {
read -p "$1:" tmp1
...
1
vote
1
answer
4k
views
Looping through a file with two columns and reading those two columns [duplicate]
I have a txt files with all the file names I need to analyze. I have this file (inputFile.txt) :
/path/file1a path/file1b
/path/file2a path/file2b
i have a code which needs two two input files in ...
3
votes
2
answers
92
views
Exit statuses of comparisons in test constructs
I was writing some "if then" statements and found what seemed to me an odd behavior. Upon investigation I realized that it boiled down to the exit code of the comparison I was making. I illustrate my ...
13
votes
6
answers
17k
views
Checking for the existence of multiple directories
I want to check for the existence of multiple directories, say, dir1, dir2 and dir3, in the working directory.
I have the following
if [ -d "$PWD/dir1" ] && [ -d "$PWD/dir2" ] && [ -...
0
votes
1
answer
123
views
Ensuring Alias /phpmyadmin /usr/share/phpmyadmin is frequent in all Apache virtual hosts whatsoever
I use Debian and Apache and say I have many virtual host files (above 20) and I want all of them to include this line in the end:
Alias /phpmyadmin /usr/share/phpmyadmin
The reason is to allow to ...
7
votes
2
answers
6k
views
How to pipe the stdout of a command, depending on the result of the exit code
Expanding from this question, we have a use case where we want to pipe the stdout of a command depending on whether that command succeeded or failed.
We start with a basic pipe
command | grep -P "...
1
vote
2
answers
292
views
How do I search a file for a pattern, then extract part of the pattern or supply a default if the pattern does not exist?
I'm trying to write a script that searches through a pre-made list of running processes across a series of machines. I'm specifically looking for rsyslogd running on those devices, and attempting to ...
0
votes
4
answers
955
views
Process a text file and create a command using shell scripting
I have a file with Server and Domain names in it as below.
Names.txt :
ABCDomain ContractABCServer_1
ABCDomain ABC_server1
LinkDomain CoreLinkServer_1
TADDomain TADServer_1
(I'm getting above file ...
4
votes
2
answers
3k
views
Append heredocument content to a file, only if this content doesn't already exist in that file
I have a file to which I want to append some content (including the first, second and third empty spaces visible in my code below):
### I am text 1
### I am text 2
(The actual text I append is way ...
-1
votes
5
answers
1k
views
Are if-fi segments necessary when iterating on a pushd-popd directory list?
I use the following code which is part of this script that I use to update my WordPress websites:
#!/bin/bash
drt="/var/www/html"
for dir in ${drt}/*/; do
if pushd "$dir"; then
wp plugin ...
2
votes
1
answer
1k
views
How bash interprets control operators
To run Rust program with a backtrace one should set environment variable RUST_BACKTRACE to one and run the program, so my first guess as inexperienced bash user was:
$ RUST_BACKTRACE=1 && ...
1
vote
2
answers
2k
views
How to run sequentially two tasks on linux [closed]
I'm using a keycloak server, when I run this command:
standalone.sh
This command launchs the server and I'm not able to stop it until I execute Ctrl-C command. I though about runing an instruction ...
0
votes
1
answer
5k
views
Syntax error near unexpected token `}' in a Bash function with an if-then statement [closed]
I stored the following script in a file and created an alias to that file in the user's bashrc, then sourced that bashrc:
#!/bin/bash
domain="$1" && test -z "$domain" && exit 2
...
11
votes
2
answers
10k
views
A while loop and an here-document - what happens when?
I have this while loop and here-document combo which I run in Bash 4.3.48(1) and I don't understand its logic at all.
while read file; do source ~/unwe/"$file"
done <<-EOF
x.sh
y.sh
EOF
...
36
votes
2
answers
8k
views
Bash "for" loop without a "in foo bar..." part
I was recently looking at some code that confused me because it works and I didn't expect it to. The code reduces to this example
#!/bin/bash
for var;
do
echo "$var"
done
When run with command line ...
-2
votes
3
answers
1k
views
Append herestring data to a file, if it doesn't already exist in that file (all in one line)
What will be an "elegant" one-line way to append a single line of data into the end of a file, with herestring, if this exact data isn't already in that file?
This is my herestring append pattern:
...
52
votes
4
answers
265k
views
Test if a string contains a substring
I have the code
file="JetConst_reco_allconst_4j2t.png"
if [[ $file == *_gen_* ]];
then
echo "True"
else
echo "False"
fi
I test if file contains "gen". The output is "False". Nice!
The ...
9
votes
2
answers
24k
views
bash - What do the brackets in if-statements do? [duplicate]
Perhaps this applies to more than just bash, but I am confused about the role of brackets in if-statements. Most examples seem to have the following format
if [ expression ]; then
#do stuff
fi
...
2
votes
5
answers
10k
views
Script to go through $PATH folders and see what executable files are available on your system
Here is what I have so far:
#!/bin/bash
for file in $PATH ; do # Scanning files in $PATH
if [ -x ] ; then #Check if executable
echo "Executable File"
else
...
1
vote
2
answers
91
views
how to keep running the script settings?
I am writing a script called pickanumber.sh. I was setting up the script so I will ask the user to pick a number. If the number that they type is not "8" than the script will continue running. I can't ...
31
votes
4
answers
7k
views
Are if else statement equivalent to logical and && or || and where should I prefer one over the other?
I'm learning about decision making structures and I came across these codes:
if [ -f ./myfile ]
then
cat ./myfile
else
cat /home/user/myfile
fi
[ -f ./myfile ] &&
cat ./myfile ||
...
-1
votes
1
answer
3k
views
Arithmetic expressions in for-loop
In
for (( expr1 ; expr2 ; expr3 )) ; do commands ; done
expr1, expr2, and expr3 are arithmetic expressions.
Is expr1 ; expr2 ; expr3 not an arithmetic expression? (( expr1 ; expr2 ; expr3 )) isn't a ...
0
votes
1
answer
1k
views
How not to proceed to the next elif if the first is true?
I have a list of text files in a directory which I want to search from terminal. To not make myself think too much, I want to be able to search for few words, example search one two three if there is ...
2
votes
1
answer
358
views
String a command after a command that ends in & - EX: nohup > log & && rm log
So I guess there is actually two parts to this question, because I don't want the RM to go untill the nohup command has finished, but the problem is, I love to string together commands, but my nohup ...
4
votes
2
answers
26k
views
How to use user input as a while loop condition
I can do this in bash:
while read -n1 -r -p "choose [y]es|[n]o"
do
if [[ $REPLY == q ]];
then
break;
else
#whatever
fi
done
which works but seems a bit redundant, can ...
1
vote
3
answers
2k
views
For loop for a set of variables
I would like to run a for loop for a set of variables which I incorrectly denote as {A,B}. Following that my script looks like:
#!/bin/sh
for {A,B} in {1,2} {3,4} {5,6} {7,8}
do
echo A=$A B=$B
C=$(($...
3
votes
5
answers
1k
views
Lots of elif, is there a better way?
I have a Bash script that looks like
#!/bin/bash
#
FECHA=`date +%j`
if [ $FECHA -eq 40 ]
then
echo "Esta semana le toca preparar el café a Osvaldo" | mail -s 'Café' [email protected]
...
442
votes
3
answers
230k
views
What are the shell's control and redirection operators?
I often see tutorials online that connect various commands with different symbols. For example:
command1 | command2
command1 & command2
command1 || command2
command1 && command2
...
109
votes
9
answers
152k
views
Press space to continue
How do I stop a bash script until a user has pressed Space?
I would like to have the question in my script
Press space to continue or CTRL+C to exit
and then the script should stop and wait until ...