Does 'Dash' Support 'Bash' Style Arrays

Does `dash` support `bash` style arrays?

dash does not support arrays. You could try something like this:

var="this is a test|second test|the quick brown fox jumped over the lazy dog"
oldIFS=$IFS
IFS="|"
set -- $var
echo "$1"
echo "$2"
echo "$3" # Note: if more than $9 you need curly braces e.g. "${10}"
IFS=$oldIFS

Note: Since the variable expansion $var is unquoted it gets split into fields according to IFS, which was set to a vertical bar. These fields become the parameters of the set command and as a result $1 $2 etc contain the sought after values.

-- (end of options) is used so that no result of the variable expansion can be interpreted as an option to the set command.

Busybox sh won't execute the bash script

Both busybox' sh (which isash) and dash do not support arrays.

You could either write a big if-else or switch case statement, or use the following trick. We simulate an array using a single string with spaces as delimiters.

cut -d ' ' -f "$1" <<< "31 28 31 30 31 30 31 31 30 31 30 31"

or even more portable:

echo "31 28 31 30 31 30 31 31 30 31 30 31" | cut -d ' ' -f "$1"

Another workaround is to abuse the script's positional parameters as seen in this answer.

Dash script to replace text false with TRUE?

Would you please try the following:

awk '
NR==FNR {a["#"$2] = $1; next} # array maps #num to "TRUE"
$NF in a {$1 = a[$NF]} # if #num is in the array, replace
1' Install.txt ExtInstaller.sh

Output:

false Styles "Diary Thumbnails" #202
TRUE Styles "My Border Style" #203
TRUE Menus "My Menu" #301
false Decorations "Diary Decor" #501
false Modules "Control Pager Button" #601
TRUE Modules "Dash To Dock" #602
TRUE Modules "Desk Switch" #603
  • The statement NR==FNR {command; next} is an idiom to execute the command
    with the file in the 1st argument (Install.txt) only.
  • a["#"$2] = $1 is an array assignment which maps e.g key #203 to value TRUE.
  • The condition $NF in a meets if the last field value $NF in the line
    of the file ExtInstaller.sh is defined as a key of array a.
  • $1 = a[$NF} replaces the 1st field false with the value of the
    array TRUE.
  • The final 1 tells awk to print current line.

Array of IP addresses in sh script

The problem is that you're running your script using a shell (namely Dash) that doesn't support a feature your script is using (namely Bash-style arrays).

The easiest fix is to change this:

#!/bin/sh

to this:

#!/bin/bash

so that your script is run using Bash instead of Dash.

Loop Variables and `unset` in Shell Script

You to avoid namespace issues .. You can fork your script and put the loop inside that fork ..

#! /bin/sh

i='1 2 3'
a='a b c'

function_to_fork(){
for i in $a; do
echo "$i"
done
}

(function_to_fork)

echo "$i"


Related Topics



Leave a reply



Submit