diff --git a/src/disk.sh b/src/disk.sh index 461461c6..2ed6f89f 100644 --- a/src/disk.sh +++ b/src/disk.sh @@ -140,8 +140,8 @@ normalizeSize() { local diskDesc="$2" local dir="$3" - local gb free space - local dataSize spare=1073741824 + local free dataSize + local spare=1073741824 if [[ "${diskSpace,,}" == "max" || "${diskSpace,,}" == "half" ]]; then @@ -154,12 +154,12 @@ normalizeSize() { fi (( free < spare )) && free="$spare" - gb=$(( free / 1073741825 )) + local gb=$(( free / 1073741825 )) diskSpace="${gb}G" fi - space="${diskSpace// /}" + local space="${diskSpace// /}" [ -z "$space" ] && space="64G" [ -z "${space//[0-9. ]}" ] && space="${space}G" space=$(echo "${space^^}" | sed 's/MB/M/g;s/GB/G/g;s/TB/T/g') @@ -618,13 +618,12 @@ addDisk () { local diskCache="$9" local fs dir used space - local diskExt diskFile - local dataSize missing + local diskExt dataSize local available currentSize - local previousExt previousFmt + local previousExt diskExt=$(fmt2ext "$diskFmt") - diskFile="$diskBase.$diskExt" + local diskFile="$diskBase.$diskExt" dir=$(dirname "$diskFile") [ ! -d "$dir" ] && return 0 @@ -647,9 +646,9 @@ addDisk () { if [ ! -f "$diskFile" ] || [ ! -s "$diskFile" ]; then if [[ "${diskFmt,,}" != "raw" ]]; then - previousFmt="raw" + local previousFmt="raw" else - previousFmt="qcow2" + local previousFmt="qcow2" fi previousExt=$(fmt2ext "$previousFmt") @@ -691,18 +690,18 @@ addDisk () { currentSize=$(getSize "$diskFile") || exit 73 used=$(du -sB 1 "$diskFile" | cut -f1) available=$(df --output=avail -B 1 "$dir" | tail -n 1) - missing=$(( currentSize - used - available )) + local missing=$(( currentSize - used - available )) (( missing < 0 )) && missing=0 if (( missing > 0 )); then - local gb base msg + local gb base gb=$(formatBytes "$available") base=$(baseDir "$dir") missing=$(formatBytes "$missing") currentSize=$(formatBytes "$currentSize") - msg="The virtual size of the ${diskDesc,,} is $currentSize" + local msg="The virtual size of the ${diskDesc,,} is $currentSize" if [ -n "$used" ] && [[ "$used" != "0" ]]; then used=$(formatBytes "$used") diff --git a/src/install.sh b/src/install.sh index dd33c4f9..77fa3eb7 100644 --- a/src/install.sh +++ b/src/install.sh @@ -14,7 +14,7 @@ getBase() { getFolder() { - local base="" + local base local result="$1" if [[ "$result" != *"."* ]]; then @@ -70,8 +70,7 @@ bootFile() { detectRawDiskMode() { local file="$1" - local result="" - local mode="" + local result mode if [ ! -r "$file" ]; then error "Failed to read disk image \"$file\"!" @@ -125,7 +124,7 @@ detectRawDiskMode() { isLegacyIso() { local file="$1" - local result="" + local result if ! result=$(LC_ALL=C xorriso \ -no_rc \ @@ -205,19 +204,12 @@ detectQcow2Mode() { local file="$1" local found="N" local protective="N" - local signature="" - local tmp="" - local type="" - local offset="" - local actual_size=0 - - local entry_lba="" - local entry_count="" - local entry_size="" - local entry_units=0 - local table_size=0 - local table_sectors=0 - local expected_size=0 + local tmp type offset + local signature actual_size + + local entry_lba + local entry_count + local entry_size if ! tmp=$(mktemp "$QEMU_DIR/boot-mode.XXXXXX"); then error "Failed to create temporary boot detection file!" @@ -316,7 +308,7 @@ detectQcow2Mode() { return 1 fi - entry_units=$((entry_size / 128)) + local entry_units=$((entry_size / 128)) if (( entry_lba < 2 || entry_count < 1 || @@ -330,7 +322,7 @@ detectQcow2Mode() { return 1 fi - table_size=$((entry_count * entry_size)) + local table_size=$((entry_count * entry_size)) # Protect against corrupt images requesting an excessive read. if (( table_size > 16777216 )); then @@ -339,8 +331,8 @@ detectQcow2Mode() { return 1 fi - table_sectors=$(((table_size + 511) / 512)) - expected_size=$((table_sectors * 512)) + local table_sectors=$(((table_size + 511) / 512)) + local expected_size=$((table_sectors * 512)) if ! readQcow2Sectors \ "$file" "$entry_lba" "$table_sectors" "$tmp"; then @@ -450,13 +442,12 @@ downloadFile() { local expected="${4:-0}" local connections="${5:-1}" local dest="$STORAGE/$base" - local msg if [ -z "$name" ]; then - msg="Downloading image" + local msg="Downloading image" info "Downloading $base..." else - msg="Downloading $name" + local msg="Downloading $name" info "Downloading $name..." fi @@ -476,7 +467,7 @@ convertImage() { local dst_file=$3 local dst_fmt=$4 local dir base fs fa space space_gb - local cur_size cur_gb src_size disk_param + local cur_size cur_gb src_size [ -f "$dst_file" ] && error "Conversion failed, destination file $dst_file already exists?" && return 1 [ ! -f "$source_file" ] && error "Conversion failed, source file $source_file does not exists?" && return 1 @@ -521,9 +512,9 @@ convertImage() { local conv_flags="-p" if [ -z "$ALLOCATE" ] || disabled "$ALLOCATE"; then - disk_param="preallocation=off" + local disk_param="preallocation=off" else - disk_param="preallocation=falloc" + local disk_param="preallocation=falloc" fi if ! fs=$(stat -f -c %T "$dir"); then diff --git a/src/network.sh b/src/network.sh index d5c44489..309f4ec3 100644 --- a/src/network.sh +++ b/src/network.sh @@ -86,7 +86,7 @@ getMTU() { minMTU() { - local mtu="" + local mtu local min="" for mtu in "$@"; do @@ -126,7 +126,7 @@ gatewayMAC() { maskToCIDR() { local mask="$1" - local prefix="" + local prefix if ! command -v ipcalc > /dev/null 2>&1; then error "Required command 'ipcalc' is not installed!" @@ -156,7 +156,7 @@ maskToCIDR() { networkCIDR() { local ip="$1" - local network="" + local network network=$(ipcalc -n -b "$ip/$MASK" 2>/dev/null | awk ' /^Network:/ { @@ -217,8 +217,7 @@ detectAddresses() { IP6="" if [ -f /proc/net/if_inet6 ] && [[ "$(cat /proc/sys/net/ipv6/conf/all/disable_ipv6 2>/dev/null)" != "1" ]]; then - local rc=0 - { IP6=$(ip -6 addr show dev "$DEV" scope global up); rc=$?; } 2>/dev/null || : + { IP6=$(ip -6 addr show dev "$DEV" scope global up); local rc=$?; } 2>/dev/null || : (( rc != 0 )) && IP6="" [ -n "$IP6" ] && IP6=$(echo "$IP6" | sed -e's/^.*inet6 \([^ ]*\)\/.*$/\1/;t;d' | head -n 1) fi @@ -228,7 +227,7 @@ detectAddresses() { detectAdapter() { - local result="" + local result NIC="" BUS="" @@ -254,7 +253,7 @@ detectAdapter() { containerID() { - local id="" + local id id=$(hostname -s 2>/dev/null || true) @@ -288,7 +287,7 @@ disableIPv6() { subnetInUse() { local subnet="$1" - local broader="" narrower="" routes="" + local broader narrower routes if ! broader=$(ip -4 route show table all match "$subnet" 2>/dev/null); then error "Failed to inspect existing routes for subnet $subnet." @@ -326,15 +325,14 @@ guestIP() { natGuestIP() { local ip="$1" - local start="" guest="" subnet="" - local second="" third="" rc="" + local guest subnet second third third=$(cut -d. -f3 <<< "$ip") if [[ "$ip" == "172.30."* ]]; then - start="31" + local start="31" else - start="30" + local start="30" fi for (( second=start; second<=254; second++ )); do @@ -344,7 +342,7 @@ natGuestIP() { if subnetInUse "$subnet"; then continue else - rc=$? + local rc=$? (( rc == 1 )) || return 1 fi @@ -359,7 +357,7 @@ natGuestIP() { if subnetInUse "$subnet"; then continue else - rc=$? + local rc=$? (( rc == 1 )) || return 1 fi @@ -413,7 +411,7 @@ configureDNS() { local host="$4" local mask="$5" local gateway="$6" - local arguments="$DNSMASQ_OPTS" rc + local arguments="$DNSMASQ_OPTS" enabled "${DNSMASQ_DISABLE:-}" && return 0 enabled "$DEBUG" && echo "Starting dnsmasq daemon..." @@ -475,7 +473,7 @@ configureDNS() { arguments=$(echo "$arguments" | sed 's/\t/ /g' | tr -s ' ' | sed 's/^ *//') enabled "$DEBUG" && printf "Dnsmasq arguments:\n\n%s\n\n" "${arguments// -/$'\n-'}" - { $DNSMASQ ${arguments:+ $arguments}; rc=$?; } || : + { $DNSMASQ ${arguments:+ $arguments}; local rc=$?; } || : if (( rc != 0 )); then @@ -498,8 +496,8 @@ configureDNS() { getHostPorts() { - local num="" list="" - local port="" ports="" + local list port + local ports="" local mode="${1:-tcp}" local display="${DISPLAY:-}" @@ -520,14 +518,14 @@ getHostPorts() { case "$mode" in "tcp" ) [[ "$port" == *"/udp" ]] && continue - num="${port%/tcp}" + local num="${port%/tcp}" ;; "all" ) if [[ "$port" == *"/udp" ]]; then - num="${port%/udp}" + local num="${port%/udp}" [ -n "$num" ] && ports+="$num/udp," else - num="${port%/tcp}" + local num="${port%/tcp}" [ -n "$num" ] && ports+="$num/tcp," fi continue @@ -554,16 +552,15 @@ getUserPorts() { [[ "${BOOT_MODE:-}" == "windows"* ]] && defaults="3389/tcp,3389/udp" local list="$defaults,${USER_PORTS// /}," - local num="" ports="" proto="" - local userport="" hostport="" + local ports="" + local userport hostport exclude - local exclude="" exclude=$(getHostPorts "all") for userport in ${list//,/ }; do - proto="tcp" - num="$userport" + local proto="tcp" + local num="$userport" if [[ "$userport" == *"/udp" ]]; then proto="udp" @@ -602,7 +599,7 @@ getUserPorts() { getSlirp() { local ip="$1" - local args="" list="" + local args="" list list=$(getUserPorts) @@ -626,9 +623,9 @@ getSlirp() { getPasst() { - local args="" list="" port="" - local num="" tcp="" udp="" + local list port local bind="$UPLINK" + local tcp="" udp="" args="" list=$(getUserPorts) @@ -638,12 +635,12 @@ getPasst() { if [[ "$port" == *"/udp" ]]; then - num="${port%/udp}" + local num="${port%/udp}" [ -n "$num" ] && udp+="$num," elif [[ "$port" == *"/tcp" ]]; then - num="${port%/tcp}" + local num="${port%/tcp}" [ -n "$num" ] && tcp+="$num," else @@ -674,7 +671,7 @@ getPasst() { configureVTAP() { - local msg="" rc=0 dev + local msg dev enabled "$DEBUG" && echo "Configuring MACVTAP networking..." @@ -686,7 +683,7 @@ configureVTAP() { fi # Create a macvtap network for the VM guest - { msg=$(ip link add link "$DEV" name "$TAP" address "$MAC" type macvtap mode bridge 2>&1); rc=$?; } || : + { msg=$(ip link add link "$DEV" name "$TAP" address "$MAC" type macvtap mode bridge 2>&1); local rc=$?; } || : case "$msg" in "RTNETLINK answers: File exists"* ) @@ -719,7 +716,7 @@ configureVTAP() { sleep 2 done - local TAP_NR TAP_PATH MAJOR MINOR + local TAP_NR MAJOR MINOR if ! dev=$(cat /sys/devices/virtual/net/"$TAP"/tap*/dev); then error "Failed to determine device numbers for MACVTAP interface \"$TAP\" !" @@ -744,7 +741,7 @@ configureVTAP() { fi # Create dev file (there is no udev in container: need to be done manually) - TAP_PATH="/dev/tap${TAP_NR}" + local TAP_PATH="/dev/tap${TAP_NR}" [[ ! -e "$TAP_PATH" && -e "/dev0/${TAP_PATH##*/}" ]] && ln -s "/dev0/${TAP_PATH##*/}" "$TAP_PATH" @@ -781,7 +778,7 @@ configureSlirp() { ip=$(guestIP "$ip" 4) local gateway="${ip%.*}.1" - local subnet="" + local subnet subnet=$(networkCIDR "$ip") || return 1 # Backwards compatibility @@ -792,7 +789,7 @@ configureSlirp() { NET_OPTS="-netdev user,id=hostnet0,ipv4=on,host=$gateway,net=$subnet,dhcpstart=$ip,${ipv6}hostname=$HOST" - local forward="" + local forward forward=$(getSlirp "$ip") [ -n "$forward" ] && NET_OPTS+=",$forward" @@ -847,7 +844,7 @@ configurePasst() { # Pass an explicit MTU to passt. PASST_OPTS+=" -m $passt_mtu" - local forward="" + local forward forward=$(getPasst) [ -n "$forward" ] && PASST_OPTS+="$forward" @@ -883,11 +880,10 @@ configurePasst() { if ! "$PASST" ${PASST_OPTS:+$PASST_OPTS} >/dev/null 2>&1; then - local rc=0 rm -f "$log" PASST_OPTS="${PASST_OPTS/ -q/}" - { "$PASST" ${PASST_OPTS:+$PASST_OPTS}; rc=$?; } || : + { "$PASST" ${PASST_OPTS:+$PASST_OPTS}; local rc=$?; } || : if (( rc != 0 )); then [ -f "$log" ] && [ -s "$log" ] && cat "$log" @@ -918,10 +914,10 @@ configurePasst() { createBridge() { local gateway="$1" - local rc msg="" + local msg # Create a bridge with a static IP for the VM guest - { msg=$(ip link add dev "$BRIDGE" type bridge 2>&1); rc=$?; } || : + { msg=$(ip link add dev "$BRIDGE" type bridge 2>&1); local rc=$?; } || : if (( rc != 0 )); then enabled "$ROOTLESS" && ! enabled "$DEBUG" && return 1 @@ -962,10 +958,10 @@ createBridge() { createTap() { local tuntap="$1" - local rc msg="" + local msg # Set tap to the bridge created - { msg=$(ip tuntap add dev "$TAP" mode tap 2>&1); rc=$?; } || : + { msg=$(ip tuntap add dev "$TAP" mode tap 2>&1); local rc=$?; } || : if (( rc != 0 )); then enabled "$ROOTLESS" && ! enabled "$DEBUG" && return 1 @@ -1008,7 +1004,7 @@ hasTable() { getTablesBackend() { - local version="" + local version version=$(iptables --version 2>/dev/null || true) case "$version" in @@ -1021,7 +1017,7 @@ getTablesBackend() { setTables() { local mode="$1" - local path="" + local path path=$(command -v "iptables-$mode" 2>/dev/null || true) [ -z "$path" ] && return 1 @@ -1035,7 +1031,7 @@ showRules() { local chain="$2" local label="$3" local rule_tag="$4" - local rules="" + local rules local own_rule="--comment[[:space:]]+\"?$rule_tag\"?([[:space:]]|\$)" enabled "$DEBUG" || return 0 @@ -1054,7 +1050,7 @@ showRules() { checkExistingTables() { - local msg="" rules="" conflicts="" + local rules conflicts local rule_tag="QEMU_DNAT" local own_rule="--comment[[:space:]]+\"?$rule_tag\"?([[:space:]]|\$)" @@ -1072,7 +1068,7 @@ checkExistingTables() { <<< "$rules" || true) if [ -n "$conflicts" ]; then - msg="your existing NAT rules may take precedence over VM port forwarding" + local msg="your existing NAT rules may take precedence over VM port forwarding" if enabled "$DEBUG"; then warn "${msg}." @@ -1092,7 +1088,7 @@ checkExistingTables() { <<< "$rules" || true) if [ -n "$conflicts" ]; then - msg="your existing firewall rules may block traffic forwarded to or from the VM" + local msg="your existing firewall rules may block traffic forwarded to or from the VM" if enabled "$DEBUG"; then warn "${msg}." @@ -1120,13 +1116,13 @@ runTableRule() { local silent="$1" local result="$2" - local rc msg="" + local msg shift 2 printf -v "$result" '%s' "" - { msg=$("$@" 2>&1); rc=$?; } || : + { msg=$("$@" 2>&1); local rc=$?; } || : (( rc == 0 )) && return 0 printf -v "$result" '%s' "$msg" @@ -1186,8 +1182,8 @@ applyTables() { local ip="$1" local subnet="$2" local silent="${3:-N}" - local exclude="" port="" - local table_error="" + local exclude port + local table_error local dnat_chain="QEMU_DNAT" local rule_tag="$dnat_chain" @@ -1315,8 +1311,8 @@ applyTables() { clearTables() { - local table="" line="" chain="" - local rules="" remaining="" message="" + local line + local rules remaining message local dnat_chain="QEMU_DNAT" local rule_tag="$dnat_chain" local own_rule="--comment[[:space:]]+\"?$rule_tag\"?([[:space:]]|\$)" @@ -1341,15 +1337,15 @@ clearTables() { while IFS= read -r line; do case "$line" in - \*nat ) table="nat" ;; - \*filter ) table="filter" ;; - \*mangle ) table="mangle" ;; - \*raw ) table="raw" ;; + \*nat ) local table="nat" ;; + \*filter ) local table="filter" ;; + \*mangle ) local table="mangle" ;; + \*raw ) local table="raw" ;; esac if [[ "$line" == -A* ]] && [[ "$line" =~ $own_rule ]]; then - chain="${line#-A }" + local chain="${line#-A }" chain="${chain%% *}" # Rules inside this chain are removed together by the flush below. @@ -1415,7 +1411,7 @@ clearTables() { hasTaggedRules() { local save="$1" - local rules="" + local rules local dnat_chain="QEMU_DNAT" local rule_tag="$dnat_chain" local own_rule="--comment[[:space:]]+\"?$rule_tag\"?([[:space:]]|\$)" @@ -1437,9 +1433,8 @@ configureTables() { local ip="$1" local subnet="$2" - local preferred="" - local alternate="" - local alternate_save="" + local preferred + local alternate_save local preferred_clean="N" local alternate_dirty="N" @@ -1450,8 +1445,8 @@ configureTables() { } case "$preferred" in - "nft" ) alternate="legacy" ;; - "legacy" ) alternate="nft" ;; + "nft" ) local alternate="legacy" ;; + "legacy" ) local alternate="nft" ;; * ) enabled "$ROOTLESS" && ! enabled "$DEBUG" && return 1 warn "unsupported IP tables backend: $preferred" @@ -1640,7 +1635,7 @@ configureTables() { configureNAT() { local tuntap="TUN device is missing. $ADD_ERR --device /dev/net/tun" - local rc ip subnet msg="" forwarding="" + local ip subnet forwarding="" enabled "$DEBUG" && echo "Configuring NAT networking..." @@ -1648,7 +1643,8 @@ configureNAT() { if [ ! -c /dev/net/tun ]; then [ ! -d /dev/net ] && mkdir -m 755 /dev/net > /dev/null 2>&1 || : - { msg=$(mknod /dev/net/tun c 10 200 2>&1); rc=$?; } || : + local msg + { msg=$(mknod /dev/net/tun c 10 200 2>&1); local rc=$?; } || : if (( rc == 0 )); then chmod 666 /dev/net/tun @@ -1667,7 +1663,7 @@ configureNAT() { forwarding=$(< /proc/sys/net/ipv4/ip_forward) if [[ "$forwarding" != "1" ]]; then - { sysctl -w net.ipv4.ip_forward=1 > /dev/null 2>&1; rc=$?; } || : + { sysctl -w net.ipv4.ip_forward=1 > /dev/null 2>&1; local rc=$?; } || : forwarding="" [ -r /proc/sys/net/ipv4/ip_forward ] && @@ -1693,7 +1689,7 @@ configureNAT() { error "VM subnet $subnet conflicts with an existing route inside the container." return 1 else - rc=$? + local rc=$? (( rc == 1 )) || return 1 fi @@ -1710,7 +1706,7 @@ configureNAT() { NET_OPTS="-netdev tap,id=hostnet0,ifname=$TAP" if [ -c /dev/vhost-net ]; then - { exec 40>>/dev/vhost-net; rc=$?; } 2>/dev/null || : + { exec 40>>/dev/vhost-net; local rc=$?; } 2>/dev/null || : (( rc == 0 )) && NET_OPTS+=",vhost=on,vhostfd=40" fi @@ -1774,7 +1770,7 @@ compat() { local gateway="$1" local interface="$2" local samba="20.20.20.1" - local label="compat" msg="" rc + local label="compat" local err="failed to configure IP alias for backwards compatibility." [[ "$samba" == "$gateway" ]] && return 0 @@ -1789,7 +1785,8 @@ compat() { fi # Preserve the legacy 20.20.20.1 host.lan address used by older guest hosts-file entries. - { msg=$(ip address add dev "$interface" "$samba/24" label "$interface:$label" 2>&1); rc=$?; } || : + local msg + { msg=$(ip address add dev "$interface" "$samba/24" label "$interface:$label" 2>&1); local rc=$?; } || : if (( rc == 0 )); then SAMBA_INTERFACE="$samba" @@ -1819,7 +1816,7 @@ compat() { checkOS() { local iface="macvlan" - local os="" kernel="" + local os="" kernel kernel=$(uname -a) @@ -1970,7 +1967,7 @@ configureMTU() { configureMAC() { - local container="" + local container container=$(containerID) if [ -z "$MAC" ]; then @@ -2015,7 +2012,7 @@ configureMAC() { showHostInfo() { - local mtu="" host="" uplink="" prefix="" + local mtu host uplink prefix prefix=$(ip -4 -o address show dev "$DEV" scope global 2>/dev/null | awk -v ip="$UPLINK" ' @@ -2102,8 +2099,6 @@ showGuestInfo() { local mode="${NETWORK,,}" - local mode="${NETWORK,,}" - if enabled "$DHCP"; then mode="DHCP" elif isNAT; then diff --git a/src/reset.sh b/src/reset.sh index 9455f913..47edc7f7 100644 --- a/src/reset.sh +++ b/src/reset.sh @@ -44,7 +44,7 @@ detectEngine() { detectRootless() { - local uid_map="" + local uid_map uid_map=$(awk '{$1=$1; print}' /proc/self/uid_map 2>/dev/null || true) @@ -61,8 +61,6 @@ checkPrivileged() { local cap_bnd local last_cap - local max_cap - # Get the capability bounding set cap_bnd=$(grep '^CapBnd:' /proc/$$/status | awk '{print $2}') cap_bnd=$(printf "%d" "0x${cap_bnd}") @@ -71,7 +69,7 @@ checkPrivileged() { last_cap=$(cat /proc/sys/kernel/cap_last_cap) # Calculate the maximum capability value - max_cap=$(((1 << (last_cap + 1)) - 1)) + local max_cap=$(((1 << (last_cap + 1)) - 1)) if [ "$cap_bnd" -eq "$max_cap" ]; then PRIVILEGED="Y" @@ -134,9 +132,7 @@ finiteMemoryLimit() { local limit="$1" local sentinel="4611686018427387904" - local i=0 - local left="" - local right="" + local i [[ "$limit" =~ ^[0-9]+$ ]] || return 1 @@ -144,8 +140,8 @@ finiteMemoryLimit() { (( ${#limit} > ${#sentinel} )) && return 1 for (( i=0; i<${#sentinel}; i++ )); do - left="${limit:i:1}" - right="${sentinel:i:1}" + local left="${limit:i:1}" + local right="${sentinel:i:1}" (( left < right )) && return 0 (( left > right )) && return 1 @@ -156,11 +152,10 @@ finiteMemoryLimit() { getMemoryInfo() { - local host_total="" - local host_avail="" + local host_total + local host_avail local limit="" local current="" - local available="" host_total=$(free -b | awk '/^Mem:/ {print $2; exit}') host_avail=$(free -b | awk '/^Mem:/ {print $7; exit}') @@ -179,7 +174,7 @@ getMemoryInfo() { if finiteMemoryLimit "$limit" && [[ "$current" =~ ^[0-9]+$ ]]; then (( limit < RAM_TOTAL )) && RAM_TOTAL="$limit" - available=$(( limit - current )) + local available=$(( limit - current )) (( available < 0 )) && available=0 (( available < RAM_AVAIL )) && RAM_AVAIL="$available" fi diff --git a/src/utils.sh b/src/utils.sh index 55909f35..7bb3498c 100644 --- a/src/utils.sh +++ b/src/utils.sh @@ -81,7 +81,7 @@ qemuPidFile() { terminateQemu() { - local file="" + local file qemuPidFile file sKill "$file" @@ -92,7 +92,7 @@ terminateQemu() { waitQemuExit() { local timeout="${1:-10}" - local file="" + local file qemuPidFile file waitPidFile "$file" "$timeout" @@ -101,7 +101,7 @@ waitQemuExit() { waitQemuPid() { local -n _pid="$1" - local cnt=0 value="" + local cnt=0 value while ! readQemuPid value; do sleep 0.02 @@ -116,7 +116,7 @@ waitQemuPid() { forceKillQemu() { local reason="$1" - local pid="" display + local pid display ! readQemuPid pid && return 0 ! isAlive "$pid" && return 0 @@ -130,11 +130,11 @@ forceKillQemu() { cleanupHelpers() { - local var value + local var local pids=() for var in "${HELPER_PIDS[@]}"; do - value="${!var:-}" + local value="${!var:-}" [ -n "$value" ] && pids+=( "$value" ) done @@ -148,7 +148,7 @@ cleanupHelpers() { startConsole() { local output="${1:-/dev/tty}" - local cnt=0 pid="" + local cnt=0 rm -f -- "$CONSOLE_SOCKET" "$CONSOLE_PID" @@ -162,7 +162,7 @@ startConsole() { exec nc -lU "$CONSOLE_SOCKET" "$output" ) & - pid=$! + local pid="$!" echo "$pid" > "$CONSOLE_PID" while [ ! -S "$CONSOLE_SOCKET" ]; do @@ -260,7 +260,7 @@ waitForShutdown() { local pid="$1" local name="$APP" - local slp cnt=0 + local cnt=0 if [[ "$name" == "QEMU" ]]; then name="the virtual machine" @@ -269,7 +269,7 @@ waitForShutdown() { while (( cnt <= wait_until && SHUTDOWN_SKIP == 0 )); do sleep 1 & - slp=$! + local slp="$!" # Stop waiting if the process has exited ! isAlive "$pid" && break @@ -421,7 +421,7 @@ waitPid() { waitPidFile() { local i=0 - local pid="" + local pid local file="$1" local timeout="${2:-10}" @@ -488,7 +488,7 @@ fKill() { sKill() { - local pid="" + local pid local file="$1" [ ! -s "$file" ] && return 0 @@ -668,8 +668,7 @@ restoreState() { escape () { - local s - s=${1//&/\&} + local s=${1//&/\&} s=${s//\<} s=${s//>/\>} s=${s//'"'/\"} @@ -695,7 +694,7 @@ html() { local title local body - local script + local script="${2:-}" local footer title=$(escape "$APP") @@ -707,8 +706,6 @@ html() { body="
${body/.../}
" fi - [ -n "${2:-}" ] && script="$2" || script="" - local HTML HTML=$(<"$TEMPLATE") HTML="${HTML/\[1\]/$title}" @@ -880,7 +877,7 @@ getAgent() { delay() { - local i rc + local i local seconds="$1" local msg="Retrying failed download in X seconds..." @@ -890,7 +887,7 @@ delay() { html "${msg/X/$i}" sleep 1 || { - rc=$? + local rc=$? (( rc >= 129 )) && exit "$rc" } done @@ -903,14 +900,13 @@ updateAriaProgress() { local line="$1" local status_file="$2" local status_tmp="$3" - local completed total [ -z "$status_file" ] && return 0 if [[ "$line" == *" CN:"* && "$line" =~ \#[[:xdigit:]]+[[:space:]]+([0-9]+)B/([0-9]+)B ]]; then - completed="${BASH_REMATCH[1]}" - total="${BASH_REMATCH[2]}" + local completed="${BASH_REMATCH[1]}" + local total="${BASH_REMATCH[2]}" if ! printf '%s %s\n' "$completed" "$total" > "$status_tmp" || ! mv -f -- "$status_tmp" "$status_file"; then @@ -924,8 +920,8 @@ updateAriaProgress() { showAriaLine() { local line="$1" - local current total progress percent speed eta - local current_size total_size speed_size output + local percent speed_size + local current_size total_size [[ "$line" == *" CN:"* ]] || return 1 @@ -933,14 +929,14 @@ showAriaLine() { return 1 fi - current="${BASH_REMATCH[1]}" - total="${BASH_REMATCH[2]}" + local current="${BASH_REMATCH[1]}" + local total="${BASH_REMATCH[2]}" current_size=$(formatBytes "$current") || current_size="${current}B" total_size=$(formatBytes "$total") || total_size="${total}B" if (( total > 0 )); then - progress=$((current * 1000 / total)) + local progress=$((current * 1000 / total)) (( progress > 1000 )) && progress=1000 printf -v percent '%d.%d' \ @@ -950,18 +946,18 @@ showAriaLine() { percent="0.0" fi - output=$'\033[35m[ \033[0m' + local output=$'\033[35m[ \033[0m' output+=$'\033[36m'"${percent}%"$'\033[0m' output+=" | $current_size / $total_size" if [[ "$line" =~ DL:([0-9]+)B ]]; then - speed="${BASH_REMATCH[1]}" + local speed="${BASH_REMATCH[1]}" speed_size=$(formatBytes "$speed") || speed_size="${speed}B" output+=$' | \033[32m'"$speed_size/s"$'\033[0m' fi if [[ "$line" =~ ETA:([^]]+) ]]; then - eta="${BASH_REMATCH[1]}" + local eta="${BASH_REMATCH[1]}" output+=$' | \033[33mETA '"$eta"$'\033[0m' fi @@ -1032,7 +1028,7 @@ checkDownloadSpace() { local dest="$1" local expected="${2:-0}" - local dir available used capacity + local dir available local expected_size capacity_size [[ "$expected" =~ ^[1-9][0-9]*$ ]] || return 0 @@ -1052,7 +1048,7 @@ checkDownloadSpace() { return 1 fi - used=0 + local used=0 # Existing blocks can be reused when the destination is resumed or replaced. if [ -f "$dest" ]; then @@ -1065,7 +1061,7 @@ checkDownloadSpace() { fi fi - capacity=$((available + used)) + local capacity=$((available + used)) if (( expected > capacity )); then expected_size=$(formatBytes "$expected") || @@ -1094,7 +1090,7 @@ startDownloadProgress() { local connections="$9" local progress_path="$dest" local progress_mode="apparent" - local log_value="" status_value="" pid_value="" + local log_value status_value="" if ! log_value=$(mktemp -p "$QEMU_DIR"); then error "Failed to create temporary download log!" @@ -1129,7 +1125,7 @@ startDownloadProgress() { "$progress_mode" \ "$status_value" & - pid_value=$! + local pid_value="$!" printf -v "$log_name" '%s' "$log_value" printf -v "$status_name" '%s' "$status_value" @@ -1160,16 +1156,16 @@ downloadWithAria() { local dest="$5" shift 5 - local aria_fd="" filter_pid="" download_pid="" - local int_trap="" term_trap="" total="" - local rc_value=0 cancel_signal_value="" + local aria_fd download_pid="" + local int_trap term_trap total + local cancel_signal_value="" if ! exec {aria_fd}> >(filterAriaOutput "$status" "$aria_display"); then error "Failed to create aria2 output filter!" return 2 fi - filter_pid=$! + local filter_pid="$!" int_trap=$(trap -p INT) term_trap=$(trap -p TERM) @@ -1199,7 +1195,7 @@ downloadWithAria() { fi while true; do - rc_value=0 + local rc_value=0 wait "$download_pid" || rc_value=$? ! isAlive "$download_pid" && break @@ -1244,7 +1240,7 @@ getDownloadFailureReason() { local connections="$1" local log="$2" - local reason="" + local reason if (( connections > 1 )); then reason=$(sed -nE \ @@ -1323,11 +1319,10 @@ downloadToFile() { local aria_resume="false" local default_interval=536870912 local interval="$default_interval" - local progress_pid="" - local status="" log="" - local dir file option rc=0 run_rc=0 - local agent="" custom_agent="N" - local output="" failure="" reason="" + local progress_pid status log + local dir file option rc run_rc=0 + local agent custom_agent="N" + local output="" reason="" local cancel_signal="" if [[ ! "$connections" =~ ^[1-9][0-9]*$ ]]; then @@ -1514,7 +1509,7 @@ downloadToFile() { return 0 fi - failure="Failed to download $url" + local failure="Failed to download $url" if (( connections == 1 && rc == 3 )); then error "$failure because the file could not be written (disk full?)." @@ -1592,8 +1587,6 @@ downloadRetry() { local minimum="$5" shift 5 - local rc=0 - if [[ ! "$connections" =~ ^[1-9][0-9]*$ ]] || (( connections > 16 )); then error "The CONNECTIONS value must be between 1 and 16!" @@ -1622,12 +1615,12 @@ downloadRetry() { if validateDownloadMinimum "$dest" "$minimum"; then return 0 else - rc=$? + local rc=$? fi else - rc=$? + local rc=$? fi @@ -1662,12 +1655,12 @@ downloadRetry() { if validateDownloadMinimum "$dest" "$minimum"; then return 0 else - rc=$? + local rc=$? fi else - rc=$? + local rc=$? fi