bashscript
                                
                                 bashscript copied to clipboard
                                
                                    bashscript copied to clipboard
                            
                            
                            
                        How would you define scopes in bash?
I have been working on a transpiler myself and came across this repo today. The specification in the README gives me some really good ideas! Thanks!
I am stuck at a point on how to implement variable scopes like:
let i = 10;
let z= 20;
while(i<10){
  console.log(i)
   i = i +1;
   let z = 40;
}
at the moment, translates to:
i=0
z=0
while  ((  $(($i < 10)) )) ; do 
  
  echo  "$i"
  i=$(($i + 1))
  z=$i
done
Let me know if you have any good idea for implementing scopes. Here is the one that I am working on https://github.com/evnix/BashType (very much a work in progress and the reason for building it exactly the same as yours 😛)
A JavaScript/TypeScript to bash transpiler. Work in progress.
Why? Mainly because I wanted to learn how to make a transpiler.
I also wanted to experiment with bash and how far we could stretch this old, yet widely cross-platform language.
Hi @avierr, we should collaborate ;)
There's a couple of things you could do:
- extract the body to function and transpile all declarations as locals
function run() {
  local -i i=0
  local -i z=0
  function extractedWhile() {
    echo "$i"
    i=$(($i + 1))
    local -i z="$i"
  }
  while (($i < 10)); do
    extractedWhile
  done
  echo "z is $z"
}
run
Works as in JavaScript and outputs:
0
1
2
3
4
5
6
7
8
9
z is 0
- You could also do variable renaming, like babel does. Since you already know the scope and which variables should be visible in which scope, you could simply rename the inner zlocal to a non-conflicting variable consistently within that scope:
function run() {
  local -i i=0
  local -i z=0
  local -i _z
  while (($i < 10)); do
    echo "$i"
    i=$(($i + 1))
    _z="$i"
  done
  echo "z is $z"
}
run
Some inspiring reading & tools here:
- https://medium.com/webpack/better-tree-shaking-with-deep-scope-analysis-a0b788c0ce77
- https://mazurov.github.io/escope-demo/
- https://github.com/estools/escope