Which command creates a local variable inside a Bash function?

Study for the OSCP Linux Exam. Use our flashcards and multiple-choice questions to test your skills. Each query comes with detailed hints and explanations to enhance your preparedness. Get ready to conquer the exam!

Multiple Choice

Which command creates a local variable inside a Bash function?

Explanation:
Inside a Bash function, creating a variable that stays confined to that function uses the local builtin. It declares the variable with function scope, so it exists only while the function runs and its value won’t leak into the surrounding script once the function returns. This is what gives you clean isolation of data inside the function. Export, on the other hand, marks a variable to be part of the environment for the current shell and any child processes, which makes it global rather than local to the function. The declare command can set up variables and, with the -g flag, makes a global variable instead of local to the function. Setlocal isn’t a Bash builtin, so it isn’t used for this purpose. So the method to create a local variable inside a Bash function is to use the local command, for example: local bob.

Inside a Bash function, creating a variable that stays confined to that function uses the local builtin. It declares the variable with function scope, so it exists only while the function runs and its value won’t leak into the surrounding script once the function returns. This is what gives you clean isolation of data inside the function.

Export, on the other hand, marks a variable to be part of the environment for the current shell and any child processes, which makes it global rather than local to the function. The declare command can set up variables and, with the -g flag, makes a global variable instead of local to the function. Setlocal isn’t a Bash builtin, so it isn’t used for this purpose.

So the method to create a local variable inside a Bash function is to use the local command, for example: local bob.

Subscribe

Get the latest from Passetra

You can unsubscribe at any time. Read our privacy policy