Variable running on its own

Asked

Viewed 32 times

1

I am trying to create a variable that I will only use when I want to create a folder. But this same variable is creating this folder before the IF condition and the READ condition are executed. Follow the simplified example:

#!/bin/bash

criar=$(mkdir API)

echo "Deseja criar a pasta raiz: "
echo "1 - Sim"
echo "2 - Não"
read opcao

if [ $opcao = "1" ]
  then 
      $criar
  else
      echo error
fi

1 answer

1


The problem is that the $(), a command override, will capture the value of the command you pass in and, in your case, insert into the variable criar. This makes the command mkdir is executed during the declaration of that variable.

Since you apparently want to create a block of code that will be executed later, it is ideal to create a function. In the example below, we create the function criar:

#!/bin/bash

# Definimos a função `criar`:
criar() {
  mkdir API
}

echo "Deseja criar a pasta raiz: "
echo "1 - Sim"
echo "2 - Não"
read opcao

if [ $opcao = "1" ]; then
    criar
  else
    echo "Usuário selecionou: Não."
fi

You can even create a check inside the function, to prevent the command mkdir is executed if the directory already exists:

criar() {
  folder_name="API"

  if [ ! -d "./$folder_name" ]; then
    mkdir $folder_name
  else
    echo "A pasta já existe."
  fi
}
  • Thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.