Sample Header Ad - 728x90

Unix & Linux Stack Exchange

Q&A for users of Linux, FreeBSD and other Unix-like operating systems

Latest Questions

3 votes
2 answers
301 views
How to handle a missing environment variable set in `crontab`
I have a `bash` script that I need to be able to start from either: 1. `cron` 2. an interactive (logon) shell This script needs to know whether it was started from `cron`, or started from an interactive shell. I thought I had resolved this issue when I declared an environment variable in the `root c...
I have a bash script that I need to be able to start from either: 1. cron 2. an interactive (logon) shell This script needs to know whether it was started from cron, or started from an interactive shell. I thought I had resolved this issue when I declared an environment variable in the root crontab:
RUN_BY_CRON="TRUE"
In the script, I test RUN_BY_CRON and use the result to set another variable:
if [ "$RUN_BY_CRON" = "TRUE" ]; then            
    ((wait_time=DELAY_HALT*60))
fi
This worked until I added set -u to my script (as a *"common defensive programming strategy"*). Since then, when I run the script from the command line, set -u flags RUN_BY_CRON as an "unbound variable" error:
$ sudo ./skedrtc.sh
./skedrtc.sh: line 24: RUN_BY_CRON: unbound variable
FWIW, I ran shellcheck on this script, and got no warning or error. I tried adding a test for RUN_BY_CRON, but got the same error. I tried testing for an interactive shell, but testing from within the script itself isn't helpful:
...
if [ -z "$RUN_BY_CRON" ]; then        # test for null string
    RUN_BY_CRON="FALSE"
fi
...

if [[ $- == *i* ]]; then              # test for interactive shell
    RUN_BY_CRON="FALSE"
fi
This feels like a [*"catch 22"*](https://www.merriam-webster.com/dictionary/catch-22) situation. I've looked for ways to create a **try-catch** block, but AIUI there's nothing like that in bash. ### Q: How can I avoid this "unbound variable" error without removing the set -u ?
Seamus (3772 rep)
Jan 19, 2025, 11:29 PM • Last activity: Jan 24, 2025, 12:20 AM
85 votes
5 answers
76475 views
How to export variables that are set, all at once?
`set` command displays all the local variables like below. How do I export these variables all at once? >set a=123 b="asd asd" c="hello world"
set command displays all the local variables like below. How do I export these variables all at once? >set a=123 b="asd asd" c="hello world"
Neerav (3245 rep)
Jun 11, 2013, 08:23 PM • Last activity: Jan 21, 2025, 06:28 PM
3 votes
1 answers
167 views
Treat unset variables as an error when substituting (set -u) ignores array expansion
I don't understand why the array expression is fine. ``` $ set -eu $ echo "${envs[*]}" $ echo "${envs}" bash: envs: unbound variable ``` How can I make bash fail also on such array expansion?
I don't understand why the array expression is fine.
$ set -eu 
$ echo "${envs[*]}"

$ echo "${envs}"
bash: envs: unbound variable
How can I make bash fail also on such array expansion?
Jakub Bochenski (325 rep)
Sep 13, 2024, 11:33 AM • Last activity: Sep 13, 2024, 01:21 PM
13 votes
3 answers
961 views
Inconsistent “unzip -l … | grep -q …” results with pipefail
The following Bash function gave inconsistent results: ```bash # $1 Path to ZIP archive. # Exits with 0 status iff it contains a “.mp3” or “.flac” file. mp3_or_flac_in_zip() { local archive=${1:?No archive given.} ( set -o pipefail unzip -l "$archive" | grep -iqE '.\.(flac|mp3)$' ) } ``` When run _n...
The following Bash function gave inconsistent results:
# $1    Path to ZIP archive.
# Exits with 0 status iff it contains a “.mp3” or “.flac” file.
mp3_or_flac_in_zip() {
    local archive=${1:?No archive given.}
    (
        set -o pipefail
        unzip -l "$archive" | grep -iqE '.\.(flac|mp3)$'
    )
}
When run _n_ times in a row on the same music-containing ZIP, it randomly reported that there was no music in it (about 1–5 % of the time, but it varied greatly across ZIPs). Switching to **an intermediate variable instead of a pipe** (with && instead of set -o pipefail to still make sure unzip was running fine) fixed the inconsistencies:
# $1    Path to ZIP archive.
# Exits with 0 status iff it contains a “.mp3” or “.flac” file.
mp3_or_flac_in_zip() {
    local archive=${1:?No archive given.}
    local listing
    listing=$(unzip -l "$archive") &&
    grep -iqE '.\.(flac|mp3)$' <<< "$listing"
}
What could be the issue, there? And are there other contexts where pipes are not such a good idea?
Alice M. (389 rep)
Aug 25, 2024, 02:51 PM • Last activity: Aug 26, 2024, 05:42 AM
2 votes
1 answers
257 views
How to suppress output for set +v / set +o verbose (disabling verbose flag) in bash?
Script ```shell #!/bin/bash set -v echo "verbose echo" { set +v; } &>/dev/null echo "non verbose echo" ``` gives the following output: ``` echo "verbose echo" verbose echo { set +v; } &>/dev/null non verbose echo ``` I want to suppress output for `{ set +v; } &>/dev/null` and get the following outpu...
Script
#!/bin/bash
set -v
echo "verbose echo"
{ set +v; } &>/dev/null
echo "non verbose echo"
gives the following output:
echo "verbose echo"
verbose echo
{ set +v; } &>/dev/null
non verbose echo
I want to suppress output for { set +v; } &>/dev/null and get the following output:
echo "verbose echo"
verbose echo
non verbose echo
I tried the approach above which is described [here](https://stackoverflow.com/a/64644990/1455694) for suppressing output for disabling xtrace (x) flag with command { set +x; } &>/dev/null and it is working for this xtrace flag. Have not found related info in manuals for bash and set. As work around this can be achieved by means of subshell call like shown [here](https://stackoverflow.com/a/19392242/1455694) . But is this possible without using subshell?
Anton Samokat (289 rep)
Jul 26, 2024, 06:57 AM • Last activity: Jul 26, 2024, 08:17 AM
2 votes
2 answers
345 views
set -o xtrace for just one line?
bash 4.4.20(1) on RHEL 8.4. `set -x ; ./blarge ; set +x` *works*, of course, but it's just that much more *stuff* to remember to remove when you're finished. And gets sticky if you're running ssh, sudo, etc. Thus, as mentioned in the Subject, is there some way to tell `set -x` to work just on one li...
bash 4.4.20(1) on RHEL 8.4. set -x ; ./blarge ; set +x *works*, of course, but it's just that much more *stuff* to remember to remove when you're finished. And gets sticky if you're running ssh, sudo, etc. Thus, as mentioned in the Subject, is there some way to tell set -x to work just on one line, as FOO=bar ./blarge sets the FOO variable to barge just for that one execution of blarge? declare Srv=s1.example.com declare DB=a_db declare Tables="-t table1 -t table2" date +"%F %T, %a Starting" set -x vacuumdb --host=$Srv -j2 --dbname=$DB $Tables --analyze set +x date +"%F %T, %a Finished"
RonJohn (1421 rep)
Jun 12, 2024, 02:58 PM • Last activity: Jun 12, 2024, 07:15 PM
0 votes
1 answers
67 views
How to unset SHELLOPTS monitor:notify?
I like getting notified immediately when a background process exits. To do that one uses: $ set -b When you do that, it sets the shell option, contained in the BUILTIN variable SHELLOPTS, called "monitor"; it changes from just "monitor" to "monitor:notify". But what if I want to return it to the def...
I like getting notified immediately when a background process exits. To do that one uses: $ set -b When you do that, it sets the shell option, contained in the BUILTIN variable SHELLOPTS, called "monitor"; it changes from just "monitor" to "monitor:notify". But what if I want to return it to the default status of only giving notification when the shell is about to issue a new prompt? I tried unset with the following result: $ unset -b bash: unset: -b: invalid option unset: usage: unset [-f] [-v] [-n] [name ...] It obviously doesn't work! I dug through the BASH man page and looked under the shopt command but didn't find anything that addressed this, but then perhaps I didn't recognize what I was looking for.
Richard T (268 rep)
May 26, 2024, 06:50 PM • Last activity: May 27, 2024, 05:40 AM
4 votes
2 answers
16854 views
Handling long-options with getopts
I am parsing options with `getopts` but would like to handle long-options as well. print-args () { title="$1" ; shift printf "\n%s\n" "${title}: \$@:" for arg in "$@"; do (( i = i + 1 )) printf "%s |%s|\n" "${i}." "$arg" done } getopts_test () { aggr=() for arg in "$@"; do case $arg in ("--colour"|"...
I am parsing options with getopts but would like to handle long-options as well. print-args () { title="$1" ; shift printf "\n%s\n" "${title}: \$@:" for arg in "$@"; do (( i = i + 1 )) printf "%s |%s|\n" "${i}." "$arg" done } getopts_test () { aggr=() for arg in "$@"; do case $arg in ("--colour"|"--color") aggr+=( "-c" ) ;; ("--colour="*|"--color="*) aggr+=( "-c" "${arg#*=}" ) ;; (*) aggr+=( "$arg" ) ;; esac done print-args "print" "$@" eval set -- "${aggr[@]}" print-args "eval" "$@" set -- "${aggr[@]}" print-args "set" "$@" local OPTIND OPTARG local shortopts="C:" while getopts "$shortopts" arg; do case $arg in ("c") context="$OPTARG" ;; (*) break ;; esac done shift $(( OPTIND - 1 )) } But I wonder whether the use of set -- "${aggr[@]}" is correct. Or is the following (using eval) more appropriate? eval set -- "${aggr[@]}" I have performed a test shown below. With eval, the string "Gunga Din" is split up, whereas with set -- "${aggr[@]}", it is being parsed correctly as a single string. getopts_test -f -g 130 --colour="170 20" "Gunga Din" print: $@: 1. |-f| 2. |-g| 3. |130| 4. |--colour=170 20| 5. |Gunga Din| eval: $@: 1. |-f| 2. |-g| 3. |130| 4. |-c| 5. |170| 6. |20| 7. |Gunga| 8. |Din| set: $@: 1. |-f| 2. |-g| 3. |130| 4. |-c| 5. |170 20| 6. |Gunga Din| Then I ran another function that uses the non-GNU getopt. getopt_test () { shortopts="Vuhv::H::w::e::n::l::C:" shortopts="${shortopts}bgcrmo" longopts="version,usage,help,verbosity::" longopts="${longopts},heading::,warning::,error::" longopts="${longopts},blu,grn,cyn,red,mgn,org" opts=$( getopt -o "$shortopts" -l "$longopts" -n "${0##*/}" -- "$@" ) print-args "\$@:" "$@" print-args "opts:" "$opts" set -- "$opts" print-args "set -- \"$opts\"" "$@" eval set -- "$opts" print-args "eval set -- \"$opts\"" "$@" } This resulted in the following getopt_test --warning=3 "foo'bar" "Gunga Din" $@: 1. |--warning=3| 2. |foo'bar| 3. |Gunga Din| opts: 1. | --warning '3' -- 'foo'\''bar' 'Gunga Din'| set -- "$opts" 1. | --warning '3' -- 'foo'\''bar' 'Gunga Din'| eval set -- "$opts" 1. |--warning| 2. |3| 3. |--| 4. |foo'bar| 5. |Gunga Din| As shown the result of getopt is a single entry with positional arguments re-arranged. This shows the need to use eval set -- "$opts" to split the positional arguments in the opts string into five entries for option parsing and processing.
Vera (1363 rep)
Oct 30, 2021, 09:46 AM • Last activity: Dec 18, 2023, 04:43 PM
11 votes
3 answers
16242 views
What is `set -o keyword` doing on bash?
What function exactly is the "**keyword**" option assigned by the `set` command on bash shell? OPTION: - `set -o keyword` OR `set -k` A simple example is enough for me to understand.
What function exactly is the "**keyword**" option assigned by the set command on bash shell? OPTION: - set -o keyword OR set -k A simple example is enough for me to understand.
testter (1510 rep)
Jan 27, 2020, 01:14 PM • Last activity: Dec 9, 2023, 02:56 PM
0 votes
0 answers
22 views
What does "set -- command doas $@" do in my Bash function?
I use this Bash oneliner, `set -o errexit;set -o pipefail;set -o nounset;doas() { [[ "${EUID}" == '0' ]]||set -- command doas "${@}";"${@}";}` in the head of my scripts in order to prevent me from being asked for a password when I'm root. [From what I gathered][1], if any arguments follow `--`, then...
I use this Bash oneliner, set -o errexit;set -o pipefail;set -o nounset;doas() { [[ "${EUID}" == '0' ]]||set -- command doas "${@}";"${@}";} in the head of my scripts in order to prevent me from being asked for a password when I'm root. From what I gathered , if any arguments follow --, then the the positional parameters are set to the arguments. What does commanddo in my oneliner? Is it a Bash bult-in (which command returns nothing)? Would someone decode it and give another example of using command. Where can I read more about command?
John Smith (827 rep)
Nov 2, 2023, 06:22 AM
0 votes
1 answers
2526 views
Setting time with clock_settime without having root access
I have written a C program that syncs the time with the time from a GPS reciever. The computer is running Ubuntu 16.04 LTS. The program uses clock_settime(CLOCK_REALTIME, &timespec) to set the time. The program is executed in a bash script, and I cannot use sudo as the script is launched by the use...
I have written a C program that syncs the time with the time from a GPS reciever. The computer is running Ubuntu 16.04 LTS. The program uses clock_settime(CLOCK_REALTIME, ×pec) to set the time. The program is executed in a bash script, and I cannot use sudo as the script is launched by the use of a desktop file. Anyone has an idea ? NB: The script is executing multiple programs, that I do not want to execute as root
Morten Skovgaard (1 rep)
Feb 28, 2018, 03:51 PM • Last activity: Aug 31, 2023, 06:06 PM
1 votes
1 answers
4550 views
batch curl request w/ https address txt file
I have multiple phones I am trying to obtain the up time for phones. I have enabled REST API for all phones and am looking to run CURL scripts to get the value of uptime. I have a script to get the value off of a Polycom phone. The below command works but I have over 3000 devices I would like to do...
I have multiple phones I am trying to obtain the up time for phones. I have enabled REST API for all phones and am looking to run CURL scripts to get the value of uptime. I have a script to get the value off of a Polycom phone. The below command works but I have over 3000 devices I would like to do this with. When I run a script of 100 commands I get the output but it is all jumbled together. I have a txt and excel file with all of the IP Adresses of the phones, the username and passwords are the same for all 3000 devices. I am looking for a way to run all commands and then get a text file with the IPADDRESS and return result of the request( IPADRESS:"Status": "2000"" or something similar). I mostly want an easy way to see the results of each curl line per IP address. ***Command*** curl -d "{\"data\": [\"UpTimeSinceLastReboot\"]}" -H "Content-Type: application/json" -k https://USERNAME:PASSWORD@IPADDRESS/api/v1/mgmt/config/get ***Output*** {“Status”: “2000”, “data”: {"UpTimeSinceLastReboot": ""} I was able to add >> /tmp/filename.txt to output a txt file with all of the responses but there was no way to accurately coorilate that to the phone's IP address..
mdbrown (11 rep)
Aug 6, 2019, 03:35 AM • Last activity: May 12, 2023, 04:11 AM
8 votes
3 answers
8565 views
`set -x` debugging my `.zshrc`
When I use `set -x` to debug a command it output some extra lines. % set -x +precmd_update_git_vars:1> [ -n '' ']' +precmd_update_git_vars:1> [ '!' -n '' ']' +precmd_update_git_vars:2> update_current_git_vars +update_current_git_vars:1> unset __CURRENT_GIT_STATUS +update_current_git_vars:3> [[ pytho...
When I use set -x to debug a command it output some extra lines. % set -x +precmd_update_git_vars:1> [ -n '' ']' +precmd_update_git_vars:1> [ '!' -n '' ']' +precmd_update_git_vars:2> update_current_git_vars +update_current_git_vars:1> unset __CURRENT_GIT_STATUS +update_current_git_vars:3> [[ python == python ]] +update_current_git_vars:4> _GIT_STATUS=+update_current_git_vars:4> python /home/ismail/zshfiles/gitstatus.py +update_current_git_vars:4> _GIT_STATUS='' +update_current_git_vars:6> __CURRENT_GIT_STATUS=( '' ) +update_current_git_vars:7> GIT_BRANCH='' +update_current_git_vars:8> GIT_AHEAD='' +update_current_git_vars:9> GIT_BEHIND='' +update_current_git_vars:10> GIT_STAGED='' +update_current_git_vars:11> GIT_CONFLICTS='' +update_current_git_vars:12> GIT_CHANGED='' +update_current_git_vars:13> GIT_UNTRACKED='' +precmd_update_git_vars:3> unset __EXECUTED_GIT_COMMAND I can't debug my commands because of these outputs. Why is set -x debugging my .zshrc? I want set -x to debug only the lines followed by set -x.
Ahmad Ismail (2998 rep)
Jul 4, 2020, 04:29 PM • Last activity: Feb 1, 2023, 01:54 AM
2 votes
1 answers
339 views
Using set -e (errexit) with block of commands and executing another on fail of that block (SC2181)
I just found out about `set -e` as I was searching for an answer to "how to run many commands (without `&&`) and immediately stop on non-zero exit code of any of them?". The `set -e` was good enough for me until I discovered that ```sh (set -e; false; echo here) || echo error ``` does produce `here`...
I just found out about set -e as I was searching for an answer to "how to run many commands (without &&) and immediately stop on non-zero exit code of any of them?". The set -e was good enough for me until I discovered that
(set -e; false; echo here) || echo error
does produce here instead of error. But as I quickly found a solution of a new problem:
(set -e; false; echo here); [ $? -ne 0 ] && echo error
I also bumped to an old problem with $? instead of if cmd ([SC2181](https://www.shellcheck.net/wiki/SC2181)) . Now I have a new question: do I just ignore the SC2181 error, or is there a proper way to make it work? I also thought about trap but I don't know if set -e produces any signal at all. --- Note that
if ! (set -e; false; echo here); then
  echo error
fi
also prints here instead of error. From [ShellCheck](https://www.shellcheck.net/wiki/SC2181) website: > Apart from the redundancy, there are other reasons to avoid this pattern: > * [...] > * Scripts that run or are called with set -e aka errexit will exit immediately if the command fails, even though they're followed by a clause that handles failure. Which means that if statement is immune to errexit or disables it. Also note that absence of () or its substitution to {} will stop execution of next commands, including error checking command. --- P.S. I want to try to have as fewer ShellCheck errors in my scripts as possible (which are almost always indicate that the script is not optimized or have bugs). In addition, executing a lot of commands with appened && operator IMHO decreases code readability and editability, therefore I want to find a cleaner solution (at least for that specific block of commands in ()).
Andrew15_5 (271 rep)
Jan 27, 2023, 06:43 AM • Last activity: Jan 27, 2023, 05:11 PM
102 votes
2 answers
66171 views
What does "set --" do in this Dockerfile entrypoint?
I'm trying to understand what this [Docker entrypoint does][1]. It seems to me that's a very common pattern when writing Dockerfiles, but my bash skills are limited and I have no idea of all the special bash symbols kung fu. Also, it's hard to google for "--", "$!" etc. What are these called in bash...
I'm trying to understand what this Docker entrypoint does . It seems to me that's a very common pattern when writing Dockerfiles, but my bash skills are limited and I have no idea of all the special bash symbols kung fu. Also, it's hard to google for "--", "$!" etc. What are these called in bash world? To summarize, what is the line bellow trying to do? if [ "${1#-}" != "$1" ]; then set -- haproxy "$@" fi
Lucas Pottersky (1123 rep)
Sep 6, 2016, 06:56 PM • Last activity: Jan 18, 2023, 10:13 AM
2 votes
1 answers
714 views
nftables Named Set Update Delay
I have the following in `nftables.conf`: table inet nat { set blocked { type ipv4_addr } chain postrouting { type nat hook postrouting priority 100; policy accept; ip daddr @blocked counter drop; oifname "ppp0" masquerade; iifname "br-3e4d90a574de" masquerade; } } The set `blocked` is a [named set](...
I have the following in nftables.conf: table inet nat { set blocked { type ipv4_addr } chain postrouting { type nat hook postrouting priority 100; policy accept; ip daddr @blocked counter drop; oifname "ppp0" masquerade; iifname "br-3e4d90a574de" masquerade; } } The set blocked is a [named set](https://wiki.nftables.org/wiki-nftables/index.php/Sets#Named_sets) which can be updated dynamically. It is in this set I wish to have a collection of IPs to block, updated every *n* minutes. In order to preserve the [atomicity](https://wiki.nftables.org/wiki-nftables/index.php/Atomic_rule_replacement) , I am **not** using the following (updateblock.sh) to update the list: #!/bin/bash sudo nft flush set inet nat blocked sudo nft add element inet nat blocked {$nodes} But rather blockediplist.ruleset: #!/usr/sbin/nft -f flush set inet nat blocked add element inet nat blocked { } I use the following order of commands: nft -f /etc/nftables.conf nft -f blockediplist.ruleset However the changes in blockediplist.ruleset are not immediately applied. I know the ruleset now contains the new IPs because the IPs are present in nft list ruleset and nft list set inet nat blocked. Even just with nft add element inet nat blocked { } is the IP not being instantly blocked. An alternative method would be to define a new set and reload nftables.conf in its entirety, though I think this would be a poor and inefficient way of doing things. Is there a way to force the changes in blockediplist.ruleset to be applied immediately? **UPDATE:** I've just discovered that when I block an IP which I haven't pinged, it gets blocked instantly. However when adding an IP to the blocklist mid-ping it takes a while for it to be blocked. When I try a set with netdev ingress the IP gets blocked instantly. Maybe this avenue of investigation might reveal something.
Synthetic Ascension (249 rep)
Sep 16, 2022, 01:29 PM • Last activity: Sep 17, 2022, 03:42 AM
0 votes
2 answers
154 views
Avoid printing of 'tee' trace line
I have the following in a script: ```` lang-bash #!/bin/bash logFile='script.log' echo -n > $logFile log="tee -a $logFile" set -x scp ... user@host:... ssh user@host " echo '...message...' " 2>&1 | $log { set +x ;} 2> /dev/null # avoids trace output of '++ set +x' ```` The output is: ```` lang-bash...
I have the following in a script:
` lang-bash
#!/bin/bash

logFile='script.log'
echo -n > $logFile
log="tee -a $logFile"

set -x
scp ... user@host:...
ssh user@host "
  echo '...message...'
  " 2>&1 | $log
{ set +x ;} 2> /dev/null  # avoids trace output of '++ set +x'
` The output is:
` lang-bash
++ ssh user@host '
  echo '\''> ...message...'\''
  '
++ tee -a script.log
> ...message...
` Can the ++ tee ... trace line be suppressed somehow, as well?
Gerold Broser (415 rep)
Jul 18, 2022, 10:26 AM • Last activity: Sep 7, 2022, 10:02 PM
1 votes
1 answers
2974 views
Ansible: set_fact after successful variable match in array
I have following playbook `~ # cat demo.yml`: ```yaml - name: demo hosts: localhost gather_facts: no vars: set: task: type: var1 task: - type: var1 - type: var2 - type: var3 tasks: - debug: var: set - debug: var: task - set_fact: task: type: "{{set.task.type if item.type is search(set.task.type|join...
I have following playbook ~ # cat demo.yml:
- name: demo
  hosts: localhost
  gather_facts: no

  vars:
    set:
      task:
        type: var1
    task:
    - type: var1
    - type: var2
    - type: var3
  
  tasks:
  - debug:
      var: set

  - debug:
      var: task

  - set_fact:
      task: 
        type: "{{set.task.type if item.type is search(set.task.type|join('|')) else 'absent'}}"
    loop: "{{task}}"
  
  - debug:
      var: task
**Output:**
PLAY [demo] ************************************************************************************************************************************************************************************************

TASK [debug] ***********************************************************************************************************************************************************************************************
ok: [localhost] => {
    "set": {
        "task": {
            "type": "var1"
        }
    }
}

TASK [debug] ***********************************************************************************************************************************************************************************************
ok: [localhost] => {
    "task": [
        {
            "type": "var1"
        },
        {
            "type": "var2"
        },
        {
            "type": "var3"
        }
    ]
}

TASK [set_fact] ********************************************************************************************************************************************************************************************
ok: [localhost] => (item={'type': 'var1'})
ok: [localhost] => (item={'type': 'var2'})
ok: [localhost] => (item={'type': 'var3'})

TASK [debug] ***********************************************************************************************************************************************************************************************
ok: [localhost] => {
    "task": {
        "type": "var1"
    }
}

PLAY RECAP *************************************************************************************************************************************************************************************************
localhost                  : ok=4    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
As you could see this works great and new value for variable task.type is set to **var1**. However the problem is when I provide set.task.type: var4 or any other variable. Than task.type is set to **var4** instead of **absent**. **Question:** How to set new value task.type: absent if set.task.type does not match any values from the array?
Rafal Niznik (333 rep)
Aug 10, 2022, 06:11 PM • Last activity: Aug 18, 2022, 02:52 PM
4 votes
2 answers
1129 views
Bash -v test doesn't work with associative arrays in 4.3.46
The `-v` unary operator that was introduced in version 4.2 to test if a variable is set or not does not appear to work in bash 4.3.46 on associative arrays. I have some bash test code that I run against a set of bash functions, and they all pass in bash 4.2 (on CentOS 7.1). I recently booted up a Lu...
The -v unary operator that was introduced in version 4.2 to test if a variable is set or not does not appear to work in bash 4.3.46 on associative arrays. I have some bash test code that I run against a set of bash functions, and they all pass in bash 4.2 (on CentOS 7.1). I recently booted up a Lubuntu 16.04.1 distro and noticed a good portion of my tests now failed, with bash 4.3.46. It seems like all of the failures are due to code like this: function is_var_set { local var="${1:?"No var provided to 'is_var_set'!"}" [[ -v "$var" ]] } declare -A array=(["a"]="element 1") is_var_set "array" Is this a widely known thing/was support removed for associative arrays?
krb686 (559 rep)
Nov 7, 2016, 12:16 AM • Last activity: Jan 1, 2022, 04:43 PM
4 votes
2 answers
1465 views
Why does this compound command {...} not exit on error, when used with ||?
I'm trying to run this script: #!/bin/bash -e { echo "Doing something"; will_fail # like `false` echo "Worked"; } || echo "Failed" To my surprise, `will_fail` failed, but I did not see "Failed" on my command line, but "Worked". Why did the compound command not exit with error after `will_fail` faile...
I'm trying to run this script: #!/bin/bash -e { echo "Doing something"; will_fail # like false echo "Worked"; } || echo "Failed" To my surprise, will_fail failed, but I did not see "Failed" on my command line, but "Worked". Why did the compound command not exit with error after will_fail failed?
Minix (6065 rep)
Sep 22, 2017, 09:40 AM • Last activity: Dec 23, 2021, 02:58 PM
Showing page 1 of 20 total questions