New answers tagged bash
1
vote
Accepted
Cancel just second command of bash logical AND operator
Just do Ctrl+z upon which fg will return with an exit code of 128+SIGTSTP, so not 0/success, so shutdown won't be run, and then fg again without a && shutdown this time.
Example:
bash-5.3$ ...
0
votes
Is there a zsh equivalent of bash builtin readarray?
For simple cases, you can use simple stream redirection. So, for a file with newlines separating single word entries, you can do something like:
my_array=($(<$filename))
and get an array. To read ...
0
votes
/usr/share/bash-completion/bash_completion parse error
You're probably running a shell other than bash when sourcing that file, which is why you are having an issue. I'm guessing that you are trying to source it from a zsh shell.
$ zsh -c 'if [[ $i =~ ^\~...
0
votes
Decode/encode base64url with common unix tools
Avoiding any external tools*:
#!/bin/bash
base64url_decode() {
local t=$1
t=${t//-/+}
t=${t//_/\/}
while [[ $(( ${#t} % 4 )) -ne 0 ]]; do
t="$t="
done
t=$(...
13
votes
Accepted
POSIX sh alternative to using [[ ... ]] in Bash
Most people use case statements for option processing because it's simple and easy and it works. There are countless examples using either built-in getopts or /usr/bin/getopt or custom/hand-crafted. ...
7
votes
POSIX sh alternative to using [[ ... ]] in Bash
expr and awk are two POSIX utilities that can do regexp matching. expr using basic regexp¹ and awk a variant of extended regexp². expr suffers from a number of design flaws and is usually considered ...
2
votes
disable bash job control warning "job specification requires leading `%'"?
Nobody has jumped the gun, the old syntax still works. But you're getting a deprecation warning: from 5.4 on, you'll be getting a failure instead.
You can fix both the future versions with a function ...
3
votes
bash syntax: what does '[@]+' mean?
TL;DR
${array[@]+"${array[@]}"} is what you need in some versions of some Korn-like shells, including bash-4.3 and older to
avoid nounset (as enabled by set -o nounset or set -u)
triggering ...
1
vote
How can I use sed to chain append lines from a text file, add it as a suffix to the text on the same lines numbers on another file, and so on?
Regarding your shell variable assignments and splitting parts into different files, there's no need for any of that:
sed -E 's@(https://([^.]+\.)*([^.]+)\.[^./]+/).*@<outline type="rss" ...
5
votes
bash syntax: what does '[@]+' mean?
Your script contains a parameter expansion (${args[@]+"${args[@]}"}) that fits into the following definition:
${parameter:+word}
If parameter is null or unset, nothing is substituted, ...
4
votes
Accepted
bash syntax: what does '[@]+' mean?
The [@] is an array subscript meaning "all the elements", the + means "Use Alternate Value".
In man bash, these are explained under "Arrays" and "Parameter Expansion&...
1
vote
Simple terminal graphics package?
gnuplot supports lots of different terminals for outputting beside dumb, many of them you can use directly on the tty (here onward I'll use tty instead of terminal to avoid confusion due to gnuplot's ...
0
votes
How can I use sed to chain append lines from a text file, add it as a suffix to the text on the same lines numbers on another file, and so on?
Your second example (the llvm stuff) is a bjillion times easier than your first example.
THING=llvm-cfi-verify
echo "--slave /usr/bin/${THING} ${THING} /usr/bin/$THING\${version}"
This ...
4
votes
How can I use sed to chain append lines from a text file, add it as a suffix to the text on the same lines numbers on another file, and so on?
For the 1st data set ...
Assumptions/understandings:
the title, text and htmlUrl attributes are derived from the last 2 dot-delimited strings in the domain (eg, for feed.site4.info we're interested ...
2
votes
How can I use sed to chain append lines from a text file, add it as a suffix to the text on the same lines numbers on another file, and so on?
Not sure about sed. But you can do it using awk and paste and some temporary files:
$ awk -F/ '{print $3}' links.txt | tee long | awk -F. '{print $1}' >short
$ paste links.txt long short > ...
6
votes
How can I use sed to chain append lines from a text file, add it as a suffix to the text on the same lines numbers on another file, and so on?
What I would do, using a template engine, here Perl's tpage from Template::Toolkit module, the clean and maintainable way:
Template:
cat rss.tmpl
<outline type="rss" title="[% title %...
7
votes
How can I use sed to chain append lines from a text file, add it as a suffix to the text on the same lines numbers on another file, and so on?
how can I use this kind of strategy: while IFS= read -r line; do echo "$line"
Don't. That's not how shells are meant to be used.
For most text processing, I'd use perl which has made sed/...
0
votes
Display Spinner while waiting for some process to finish
Another solution for macOS. Any improvements are welcome.
#!/bin/bash
spinner() {
local pid=$1
local message="${2}"
local delay=0.1
local spin='-\|/-'
local i=0
while ...
-1
votes
How do I create a directory for every file in a parent directory
Just a one-liner to copy-paste in terminal, straight into the "ParentFolder" where "File1.txt, File2.txt" are.
for x in *.txt; do mkdir "${x%.*}" && mv "$x&...
6
votes
Choice of field separator affects sort's ordering
Using a field separator with sort only makes sense if you sort on specific fields. If not, then the field separator is irrelevant. And that's why you get different sorting. So you're not seeing the ...
8
votes
How do I ensure a bash script argument is a specific value?
I suspect you can accomplish what you want in bash and in a way that is much easier for others to read and understand.
$ cat t.bash
#!/usr/bin/bash
croak() { # dying words
readonly RED=4 # ...
7
votes
How do I ensure a bash script argument is a specific value?
No need to use the Korn-style [[ ... ]] let alone Bash's =~ in there, you could use the standard case construct which would make your code more legible.
RED=$'\e[31m' RESET=$'\e[m'
die() {
while [ &...
10
votes
Accepted
How do I ensure a bash script argument is a specific value?
The main problem with your script is a boolean logic error. In your elif clause you are testing for ("not cli OR not gui") when you should be testing for ("not cli AND not gui").
...
2
votes
Accepted
White spacing is causing variable to not contain all text in result
The first parentheses pair, i.e. the ( immediately before the $(sudo...) and its matching ) at the end, are causing $result to be populated as an array.
To confirm this, try typing declare -p result
I ...
2
votes
Accepted
Process sed capture group with a bash function before replacement: "sh: 1: <bash function>: not found"
sed runs shell commands in a sub-shell of the default system shell i.e. whatever /bin/sh links to (Usually a POSIX shell like dash) that shell doesn't support exporting user defined functions (which ...
1
vote
Process sed capture group with a bash function before replacement: "sh: 1: <bash function>: not found"
Without the shebang selecting /bin/bash, your system selects /bin/sh, an older, simpler shell, that doesn't understand the bashisms you use.
Before your file's first line,
#!/bin/bash
will tell the ...
2
votes
Accepted
`xargs sh -c` not picking up last argument (vs `for i in $(...)`)
To solve what appears to be your complement requirement you can use bc
colourcode='#0C0C0C'
sixhex="${colourcode#\#}"
printf 'obase=16\nibase=16\n"FFFFFF - %s\n' "${sixhex^^}" ...
1
vote
Accepted
Shell bracket list wildcard doesn't work with variable
as you've probably guessed, because the brace expansion ({…,…}-> … …) happens before the parameter expansion ($LIST-> string stored within). From Bash manual, "3.2 Shell Expansions":
...
-1
votes
How to export variables from a file?
I use grep -v to filter comments out:
export $(grep -v "#" .env| xargs)
0
votes
Accepted
Bash Script Linux - combines a QUIET function with other functions without hiding some of them
Use #!/usr/bin/env bash instead of #!/bin/bash;
Use only lowercase for your variable names;
Do not mix echo and printf commands;
Do not mix $... and %... in printf arguments;
function fct_name () { ......
15
votes
Is there any difference between [[ -n $1 ]] and [[ $1 ]] in bash?
There's no difference. In man bash, both the possibilities are shown as identical under CONDITIONAL EXPRESSIONS:
string
-n string
True if the length of string is non-zero.
At the prompt of the bash ...
6
votes
Accepted
Bash: only the first long option is being processed
shift 2 will remove the first 2 positional parameters so skip both --first and --second. You'd use shift 2 when processing an option that takes an argument (after having stored the value in $2). Here, ...
3
votes
Accepted
Bash: function in a script with flags
The problem is the colon which links Hello to --foo instead of treating it as a non-option argument:
getopt -o '' --long foo: -n 'testing' -- --foo "Hello"
--foo 'Hello' --
getopt -o '' --...
1
vote
Nameref variables
That's right, though in bash, the implementation is much cruder than in ksh93 where the feature comes from or zsh (namerefs added in 5.10 not released yet). It's lexical there and more syntactic sugar ...
9
votes
Why doesn't the pwd nullary built-in error when provided an argument, whereas the nullary/unary exit built-in does error?
Just to give the standard (POSIX) view:
The standard pwd utility must support a -L and -P option and expects no non-option argument (other than the -- end-of-option marker).
It must follow the Utility ...
0
votes
Is dash or some other shell "faster" than bash?
In the Spring of 2025 one Pontus Lahtinen wrote a report for their Bachelor Degree Project in Informatics at the University of Skövde.
The abstract of their paper states:
This work looks at nine ...
10
votes
Accepted
Why doesn't the pwd nullary built-in error when provided an argument, whereas the nullary/unary exit built-in does error?
It's almost certainly just how they have been designed. It makes sense: pwd takes no arguments (only options, things that start with -). So it cannot get confused if it gets too many, you can't make ...
-1
votes
Match only ASCII letters in regular expression, ignoring umlauts
Here is some Perl code used to identify non-ASCII characters. I think this will accomplish what you are looking for. These characters are considered utf8, and to enable them in Perl you have to ...
0
votes
Why does bash not remove backslash in the quote removal step in this example?
The key is that within single quotes, NO special characters have any special meaning. It is just considered an entire string literal.
In your example, echo '\\abc', you had wrapped it in single quotes....
0
votes
Source file in bash to set prompt with ANSI colors
@grawity's answer worked great! Thought I'd share the result and the code that made it:
__prompt_command() {
EXIT="$?"
CLEAR="\[\e[0m\]"
RED="\[\e[91m\]"
...
1
vote
Source file in bash to set prompt with ANSI colors
You use single quotes in the PS1= assignments, preventing variable expansion from happening right there at assignment time. For PS1 that's fine as Bash will do a second expansion pass later, ...
0
votes
How to use a pattern when doing for loop of files in directory
To answer your question:
How can I modify the below code to look for the oldest file matching a pattern? If I just look for basename, I pick up a malformed filename, like filename_YYMM, which I don't ...
1
vote
How to use a pattern when doing for loop of files in directory
It would be a lot easier in zsh whose globs are functionally equivalent to regexps (though with different syntax):
set -o extendedglob
base=filename
oldest=( ${base}_[0-9](#c8).csv(N-Om[1]) )
x(#c8) ...
0
votes
Summing rows in a new column using sed, awk and perl?
Here is a Perl solution without any external libraries.
$ perl -pe 'for(split(/ +/)){$sum+=$_} s/\n/ $sum\n/;$sum=0;' sum.of.line.txt
1 11 323 335
2 13 3 18
3 44 4 51
4 66 23 93
5 70 23 98
6 34 23 63
...
0
votes
best practice for SC2155: declare and assign separately
If one uses
func() {
local VAR1; VAR1="$(echo a)"
declare -g VAR2; VAR1="$(echo b)"
}
then a shellcheck like regex can be used to find all the places it's not explicit.
0
votes
How to use a pattern when doing for loop of files in directory
The only reason to use Bash is Perl is not installed!
Here is a solution in Perl if you are interested. The steps I took were as follows.
Exit if filename.csv exists
Find all files in directory, ...
Top 50 recent answers are included
Related Tags
bash × 28052shell-script × 6993
shell × 4214
linux × 2880
scripting × 1579
awk × 1021
command-line × 990
sed × 975
terminal × 820
grep × 730
text-processing × 725
ssh × 716
find × 683
variable × 648
ubuntu × 597
io-redirection × 595
zsh × 584
pipe × 575
environment-variables × 545
files × 542
alias × 516
quoting × 508
command-history × 463
wildcards × 461
regular-expression × 447