Skip to content
Advertisement

How can I pass in this echo statement into my function in bash?

bitToSixtyFour () {

    echo "$((2#$1))"
}
while true
do
    if (( i == ${#newString} || i >= ${#newString} ))
    then
            break
    fi

    echo ${newString:i:i+6} | bitToSixtyFour

    i+=6
done

So in my while loop I am trying to figure out how to pass in the echo statement into my function bitToSixtyFour as a parameter. It is saying that bitToSixtyFour is not found.

Advertisement

Answer

As defined the function takes argument $1 from command line :

bitToSixtyFour arg1

to read from standard input read

bitToSixtyFour() {
    read varname
    echo $((2#$varname))
}

echo 1010 | bitToSixtyFour

it would be more efficient to use a variable to avoid creating subshell and pipes

bitToSixtyFour() {
    bitToSixtyFour=$((2#$1))
}

newString=1100101010011110101110110001100110
for ((i=0;i<${#newString};i+=6)); do
    substr=${newString:i:6}
    bitToSixtyFour "$substr"
    printf "%3s %sn" "$bitToSixtyFour" "$substr"
done

and with question definition

bitToSixtyFour() {
    echo "$((2#$1))"
}

newString=1100101010011110101110110001100110
for ((i=0;i<${#newString};i+=6)); do
    substr=${newString:i:6}
    res=$(bitToSixtyFour "$substr")
    printf "%3s %sn" "$res" "$substr"
done
Advertisement