#how to read text from file into an array (bash)

9 messages · Page 1 of 1 (latest)

real smelt
#

Hey all, I have this tiny bash script to grab my i3 workspace and set it, the problem I think is scope my X var is not being seen at all by the set function.

#!/bin/bash
    
function main {
    # If the argument is empty then run both functions else only run provided function as argument $1.
    [ -z "$1" ] && { get; set; } || $1     
}
        
function get {    
  X=$(i3-msg -t get_workspaces | jq -r '.[] | select(.visible == true).name')
    for var in "${X[@]}"
    do
        echo "$var"
    done
}
    
function set {    
    sleep 5;
   for var in "${X[@]}"
    do
    echo "$var"
    i3-msg workspace $var
    sleep 1;
  done  
}
    
main "$@"

would declaring the variable outside the function work, and if so why? (If I remember correctly there is local variables).
I am going to test this, but just in case it doesn't work, or even if it does I'm confused.

#

also why is running the script with get returning my variables but set won't

#

if the above was the case, and it was a scope issue, this would've worked. Set is still echoing no variables.

#!/bin/bash
X=""
    
function main {
    # If the argument is empty then run both functions else only run provided function as argument $1.
    [ -z "$1" ] && { get; set; } || $1     
}
        
function get {    
  X=$(i3-msg -t get_workspaces | jq -r '.[] | select(.visible == true).name')
    for var in "${X[@]}"
    do
        echo "$var"
    done
}
    
function set {    
    sleep 5;
   for var in "${X[@]}"
    do
    echo "$var"
    i3 workspace "$var"
    sleep 1;
  done  
}
    
main "$@"

#

could it be that I need to setup environment variables to get the state to be shared between runs.

#

?

real smelt
#

or would a simple text file work for storing the array in

#

I've gone with a text file, have been able to write to the file, the script freezes when I run set.

#!/bin/bash
    
function main {
    # If the argument is empty then run both functions else only run provided function as argument $1.
    [ -z "$1" ] && { get; set; } || $1     
}
        
function get {    
  echo "$(i3-msg -t get_workspaces | jq -r '.[] | select(.visible == true).name')" > file
}
    
function set {
     read -a X > file
     sleep 5;
   for var in "${X[@]}"
    do
    echo "$var"
    i3 workspace "$var"
    sleep 1;
  done  
}
    
main "$@"
real smelt
#

how to read text from file into an array (bash)

real smelt
#

this still isn't returning, or running the for loop.