Unix & Linux Stack Exchange
Q&A for users of Linux, FreeBSD and other Unix-like operating systems
Latest Questions
66
votes
5
answers
77077
views
What is "declare" in Bash?
After reading ilkkachu's answer to [this question][1] I learned on the existence of the `declare` (with argument `-n`) shell built in. `help declare` brings: > Set variable values and attributes. > > Declare variables and give them attributes. If no NAMEs are given, > display the attributes and valu...
After reading ilkkachu's answer to this question I learned on the existence of the
declare
(with argument -n
) shell built in.
help declare
brings:
> Set variable values and attributes.
>
> Declare variables and give them attributes. If no NAMEs are given,
> display the attributes and values of all variables.
> -n ... make NAME a reference to the variable named by its value
I ask for a general explanation with an example regarding declare
because I don't understand the man
. I know what is a variable and expanding it but I still miss the man
on declare
(variable attribute?).
Maybe you'd like to explain this based on the code by ilkkachu in the answer:
#!/bin/bash
function read_and_verify {
read -p "Please enter value for '$1': " tmp1
read -p "Please repeat the value to verify: " tmp2
if [ "$tmp1" != "$tmp2" ]; then
echo "Values unmatched. Please try again."; return 2
else
declare -n ref="$1"
ref=$tmp1
fi
}
user149572
Apr 3, 2019, 06:49 AM
• Last activity: Jun 11, 2025, 10:39 AM
1
votes
2
answers
1077
views
Cannot Display Bash Functions within FZF Preview Window
**How do I get the FZF Preview Window to Display Functions from my Current Bash Environment?** I want to list my custom bash functions using FZF, and view the code of a selected function in the FZF Preview Window. However, it does not appear that the bash enviroment used by FZF to execute my command...
**How do I get the FZF Preview Window to Display Functions from my Current Bash Environment?**
I want to list my custom bash functions using FZF, and view the code of a selected function in the FZF Preview Window.
However, it does not appear that the bash enviroment used by FZF to execute my command can see the functions in my terminal bash environment. For example:
However, the following works:
$ declare -F | fzf --preview="type {3}"
/bin/bash: line 1: type: g: not found

$ declare -F
declare -f fcd
declare -f fz
declare -f g
$ type g
g is a function
g ()
{
search="";
for term in $@;
do
search="$search%20$term";
done;
nohup google-chrome --app-url "http://www.google.com/search?q=$search " > /dev/null 2>&1 &
}
declare -F | fzf --preview="echo {3}"
g # my function g()
One reason I suspect that the FZF Preview Window environment may not be able to see my terminal environment is because they have different process ID's.
$ echo $BASHPID
1129439
$ declare -F | fzf --preview="echo $BASHPID"
1208203
**How do I get the FZF Preview Window to Display Functions from my Current Bash Environment?**
user2514157
(225 rep)
Oct 21, 2022, 03:10 PM
• Last activity: Jun 11, 2025, 07:38 AM
7
votes
1
answers
579
views
bash - how to remove a local variable (inside a function)
I've read what's listed in Bibliography regarding `unset`, `declare`, `local` and "Shell Functions". My version of Bash is ``` GNU bash, version 5.1.16(1)-release (x86_64-pc-linux-gnu) ``` ``` var='outer' declare -p var unset var declare -p var function foo { echo \""I'm in"\" local var='inner' decl...
I've read what's listed in Bibliography regarding
unset
, declare
, local
and "Shell Functions".
My version of Bash is
GNU bash, version 5.1.16(1)-release (x86_64-pc-linux-gnu)
var='outer'
declare -p var
unset var
declare -p var
function foo {
echo \""I'm in"\"
local var='inner'
declare -p var
unset var
declare -p var
}
foo
(the strange quoting around I'm in
is there just to preserve syntax highlithing in the following block quote.) This prints
declare -- var="outer"
bash: declare: var: not found
"I'm in"
declare -- var="inner"
declare -- var
There is a difference in unsetting a global variable and unsetting a local variable inside a function. In the former case, the variable is removed. In the latter, the variable stays declared (but unset).
Is there a way to completely remove a local variable inside a function (before the function returns)? That is that the output would be
declare -- var="outer"
bash: declare: var: not found
"I'm in"
declare -- var="inner"
bash: declare: var: not found
That would be useful to test if a variable is non existing inside a function, like in
function foo {
local var
while
declare -p var
do
echo "$var"
((var++))
[[ "$var" -eq 4 ]] \
&& unset var
done
}
This code loops indefinitely, printing
declare -- var="1"
1
declare -- var="2"
2
declare -- var="3"
3
declare -- var
declare -- var="1"
1
declare -- var="2"
2
declare -- var="3"
3
declare -- var
[omissis]
Is there anything wrong in checking if a variable exists using declare -p
?
The only mention I found in the Bash reference manual about the difference between unsetting a global variable and a local one is
> If a variable at the current local scope is unset, it will remain so (appearing as unset) until it is reset in that scope or until the function returns. (ref. Bash reference manual - sec. "Shell Functions")
where the word _appearing_ is the only clue.
**Bibliography**
+ [Bash reference manual] sec. "4 Shell Builtin Commands"
+ [What does unset do?]
the_eraser
(185 rep)
Dec 10, 2024, 02:09 PM
• Last activity: Dec 10, 2024, 05:34 PM
6
votes
1
answers
253
views
What is bash declare built-in reporting here?
Our RHEL8 servers don't have `nc` available, but at some time in the past someone using this shared account defined an `nc` function: ```lang-shellsession $ declare -f nc | head -1 nc () $ ``` I am trying to determine where this function is defined: ```lang-shellsession $ (shopt -s extdebug; declare...
Our RHEL8 servers don't have
nc
available, but at some time in the past someone using this shared account defined an nc
function:
-shellsession
$ declare -f nc | head -1
nc ()
$
I am trying to determine where this function is defined:
-shellsession
$ (shopt -s extdebug; declare -F nc)
nc 0 environment
$
I was expecting a line number and a filename there, and as you can see I got 0 environment
instead. Can somebody tell me what this means, please?
wytten
(163 rep)
Oct 30, 2024, 09:58 PM
• Last activity: Oct 31, 2024, 02:45 PM
1
votes
1
answers
39
views
Obtaining the delta for 'declare -F' between current and clean shell environments
Main question: how would one get the delta for `declare -F`, between that in the current shell, and that as if the shell just started (first two commands below). `$(declare -F)` does not solve the problem because [the subshell is a copy of the shell process][1]. Subsidiary: why does the third comman...
Main question: how would one get the delta for
declare -F
, between that in the current shell, and that as if the shell just started (first two commands below). $(declare -F)
does not solve the problem because the subshell is a copy of the shell process . Subsidiary: why does the third command below output nothing?
$ exec env -i bash
$ declare -F
declare -f ShowInstallerIsoInfo
declare -f __expand_tilde_by_ref
declare -f __get_cword_at_cursor_by_ref
declare -f __load_completion
declare -f __ltrim_colon_completions
declare -f __parse_options
declare -f __reassemble_comp_words_by_ref
declare -f _allowed_groups
declare -f _allowed_users
declare -f _available_interfaces
declare -f _bashcomp_try_faketty
declare -f _bq_completer
declare -f _cd
declare -f _cd_devices
declare -f _command
declare -f _command_offset
declare -f _complete_as_root
declare -f _completer
declare -f _completion_loader
declare -f _configured_interfaces
declare -f _count_args
declare -f _dvd_devices
declare -f _expand
declare -f _filedir
declare -f _filedir_xspec
declare -f _fstypes
declare -f _get_comp_words_by_ref
declare -f _get_cword
declare -f _get_first_arg
declare -f _get_pword
declare -f _gids
declare -f _have
declare -f _included_ssh_config_files
declare -f _init_completion
declare -f _installed_modules
declare -f _ip_addresses
declare -f _kernel_versions
declare -f _known_hosts
declare -f _known_hosts_real
declare -f _longopt
declare -f _mac_addresses
declare -f _minimal
declare -f _modules
declare -f _ncpus
declare -f _open_files_for_editing
declare -f _parse_help
declare -f _parse_usage
declare -f _pci_ids
declare -f _pgids
declare -f _pids
declare -f _pnames
declare -f _python_argcomplete
declare -f _quote_readline_by_ref
declare -f _realcommand
declare -f _rl_enabled
declare -f _root_command
declare -f _service
declare -f _services
declare -f _shells
declare -f _signals
declare -f _split_longopt
declare -f _sysvdirs
declare -f _terms
declare -f _tilde
declare -f _uids
declare -f _upvar
declare -f _upvars
declare -f _usb_ids
declare -f _user_at_host
declare -f _usergroup
declare -f _userland
declare -f _variables
declare -f _xfunc
declare -f _xinetd_services
declare -f dequote
declare -f quote
declare -f quote_readline
$ "$SHELL" -c 'declare -F'
Other:
$ uname -a
Linux elitebook 6.7.3-arch1-2 #1 SMP PREEMPT_DYNAMIC Fri, 02 Feb 2024 17:03:55 +0000 x86_64 GNU/Linux
$ bash --version
GNU bash, version 5.2.26(1)-release (x86_64-pc-linux-gnu)
$ echo $SHELL
/bin/bash
## Update:
> The clean state is an empty list of functions, as seen in the output of bash -c 'declare -F'
Based on the first command I expected the second to output two functions rather than zero.
$ grep -F -f I expected the second to output two functions rather than zero.
Here might be the reason for sourcing not taking effect:
$ cat ~/.bashrc
#
# ~/.bashrc
#
# If not running interactively, don't do anything
[[ $- != *i* ]] && return
Workaround does output two functions.
$ bash -c 'source /dev/null
Erwann
(729 rep)
Mar 13, 2024, 06:10 AM
• Last activity: Mar 13, 2024, 03:51 PM
5
votes
2
answers
640
views
Is the output of `declare -p <variable>` in bash guaranteed to be reusable as shell input?
This is specifically about `bash`'s `declare` - the general case is pretty exhaustively dealt with in [this answer][1] (which mentions "the `typeset`/`declare`/`export -p` output of `ksh93`, `mksh`, `zsh`" but _not_ that of `bash`). Given a local/exported/array/assocative-array (but maybe not namere...
This is specifically about
bash
's declare
- the general case is pretty exhaustively dealt with in this answer (which mentions "the typeset
/declare
/export -p
output of ksh93
, mksh
, zsh
" but _not_ that of bash
).
Given a local/exported/array/assocative-array (but maybe not nameref) variable foo
, is the output of declare -p foo
in bash
guaranteed to be reusable by bash
? The official documentation doesn't mention anything like that:
> The -p
option will display the attributes and values of each name
.
> When -p
is used with name
arguments, additional options, other
> than -f
and -F
, are ignored.
And I looked through the CHANGES
, and saw this about _functions_:
This document details the changes between this version, bash-2.05-beta1,
and the previous version, bash-2.05-alpha1.
...
b. When `set' is called without options, it prints function definitions in a
way that allows them to be reused as input. This affects `declare' and
`declare -p' as well.
And for a couple of other commands, -p
is meant to produce reusable output:
s. The shopt'
-p' option now causes output to be displayed in a reusable
format.
...
u. umask' now has a
-p' option to print output in a reusable format.
And Chet Ramey's Bash FAQ has:
Bash-2.0 contained extensive changes and new features from bash-1.14.7.
Here's a short list:
...
most builtins use -p option to display output in a reusable form
(for consistency)
But nothing I can find about declare -p
for variables.
muru
(77471 rep)
Feb 15, 2024, 04:22 AM
• Last activity: Feb 25, 2024, 10:55 AM
0
votes
1
answers
113
views
Bash create parameter named array within function
I'm attempting to write a function that writes arrays with a name that's passed in. Given the following bash function: function writeToArray { local name="$1" echo "$name" declare -a "$name" ${name[0]}="does this work?" } Running like this: writeToArray $("test") I get two errors: bash: declare: `':...
I'm attempting to write a function that writes arrays with a name that's passed in. Given the following bash function:
function writeToArray {
local name="$1"
echo "$name"
declare -a "$name"
${name}="does this work?"
}
Running like this:
writeToArray $("test")
I get two errors:
bash: declare: `': not a valid identifier
=does this work?: command not found
I am expecting to be able to do this:
writeToArray $("test")
for item in "${test[@]}"; do
echo "item"
echo "$item"
done
This should print:
item
does this work?
How could I properly configure this to write the array (named
test
in the example, such that this array named test
is readable outside the function)?
Lee
(549 rep)
Mar 8, 2023, 03:31 PM
• Last activity: Mar 8, 2023, 08:30 PM
3
votes
1
answers
411
views
Why does substituting eval with declare (for creating dynamic variables) result in an empty variable?
With bash >5, I'm trying to assign a different value to variables depending on the architecture specified in a variable. I use a function to do so. This works perfectly: # arguments: variable name to assign, value for mac arch, value for pi arch create_variable_for_arch() { if [ "$_run_for_arch" = "...
With bash >5, I'm trying to assign a different value to variables depending on the architecture specified in a variable. I use a function to do so. This works perfectly:
# arguments:
variable name to assign,
value for mac arch,
value for pi arch
create_variable_for_arch() {
if [ "$_run_for_arch" = "mac" ]; then
eval $1=\$2
else
eval $1=\$3
fi
}
However, this breaks my script for some reason:
create_variable_for_arch() {
if [ "$_run_for_arch" = "mac" ]; then
declare "$1"="$2"
else
declare "$1"="$3"
fi
}
Here is a snippet to demonstrate how I use create_variable_from_arch()
declare _moonlight_opt_audio
declare _arch_specific_stream_command
#
while getopts "b:fahdr:s" options; do
case $options in
a)
create_variable_for_arch "_moonlight_opt_audio" \
"--audio-on-host" "-localaudio"
;;
esac
done
create_variable_for_arch "_moonlight_opt_fps" "--fps 60" "-fps 60"
start_streaming() {
_arch_specific_options="$_moonlight_opt_resolution $_moonlight_opt_fps $_moonlight_opt_audio $_moonlight_opt_display_type $_moonlight_opt_bitrate"
create_variable_for_arch "_arch_specific_stream_command" "$_arch_specific_options stream $_target_computer_ip $_moonlight_opt_app_name" "stream $_arch_specific_options -app $_moonlight_opt_app_name $_target_computer_ip"
moonlight $_arch_specific_stream_command
}
The trace looks like this with eval()
+ start_streaming
+ _arch_specific_options='--resolution 1920x1080 --fps 60 --bitrate 5000'
+ create_variable_for_arch _arch_specific_stream_command '--resolution 1920x1080 --fps 60 --bitrate 5000 stream 192.168.1.30 StreamMouse' 'stream --resolution 1920x1080 --fps 60 --bitrate 5000 -app StreamMouse 192.168.1.30'
+ '[' mac = mac ']'
+ eval '_arch_specific_stream_command=$2'
++ _arch_specific_stream_command='--resolution 1920x1080 --fps 60 --bitrate 5000 stream 192.168.1.30 StreamMouse'
+ moonlight --resolution 1920x1080 --fps 60 --bitrate 5000 stream 192.168.1.30 StreamMouse
moonlight --resolution 1920x1080 --fps 60 --bitrate 5000 stream 192.168.1.30 StreamMouse
But with declare it looks like this:
+ start_streaming
+ _arch_specific_options=
+ create_variable_for_arch _arch_specific_stream_command ' stream 192.168.1.30 ' 'stream -app 192.168.1.30'
+ '[' mac = mac ']'
+ declare '_arch_specific_stream_command= stream 192.168.1.30 '
+ echo moonlight
moonlight
$_arch_specific_options ends up with no value. What is going on? I've tried a few different ways of quoting or not quoting variables, but I don't really understand what's doing what in terms of quotations.
DeadBranch
(33 rep)
Mar 3, 2021, 02:09 PM
• Last activity: Mar 4, 2021, 01:19 PM
1
votes
1
answers
54
views
correct way of storing external programm and making it executable?
I downloaded the CLI Client [habash][1] for the habit/routine gameification project [habatica.com][2]. In the [fandom wiki for habash][3] it is written that, I need to set environment variables. Additonally I want to make the program habash an ordinary CLI-program, so that I dont have to invoke it v...
I downloaded the CLI Client habash for the habit/routine gameification project habatica.com .
In the fandom wiki for habash it is written that, I need to set environment variables. Additonally I want to make the program habash an ordinary CLI-program, so that I dont have to invoke it via the fullpath.
I describe now, what I have been doing.
I did the following.
- After
declare -x HABITICA_UUID=[myUserID]
I did not find any entries in ~/.bashrc. Any one knows why?
- Therfore I added HABITICA_UUID and HABITICA_TOKEN at the top of ~/.bashrc (and made a comment for myself)
- chmod 600 ~/.bashrc
because UUID and TOKEN are regarded as PWs.
- sudo mv ./habash /opt
- sudo ln -s /opt/habash/habash /usr/local/bin
Is this the best way how to do it? (storing in /opt and linkint to /usr/local/bin ; variables in .bashrc and chmoding it with 600)
Josomeister
(61 rep)
Feb 9, 2021, 05:05 PM
• Last activity: Feb 9, 2021, 08:50 PM
1
votes
1
answers
1374
views
Using cURL, jq, and declaration and for loop condition, I tried to download multiple files from a GitLab private repo, but it downloaded only one
I learned from the following sources: - **`curl -O`**: [Download a file with curl on Linux / Unix command line](https://www.cyberciti.biz/faq/download-a-file-with-curl-on-linux-unix-command-line/) - **jq:** [How to urlencode data for curl command?](https://stackoverflow.com/questions/296536/how-to-u...
I learned from the following sources:
- **
curl -O
**: [Download a file with curl on Linux / Unix command line](https://www.cyberciti.biz/faq/download-a-file-with-curl-on-linux-unix-command-line/)
- **jq:** [How to urlencode data for curl command?](https://stackoverflow.com/questions/296536/how-to-urlencode-data-for-curl-command/34407620#34407620)
- **Multiple files and curl -J
:** https://unix.stackexchange.com/questions/91798/download-pdf-files-from-using-curl
- **Condition for
loop:** https://unix.stackexchange.com/questions/377446/shell-how-to-use-2-variables-with-for-condition and https://unix.stackexchange.com/questions/291049/unable-to-download-data-using-curl-for-loop
Description of the script:
1. Variables, required by GitLab's [Repository files API](https://docs.gitlab.com/ee/api/repository_files.html) :
branch="master"
repo="my-dotfiles"
private_token="XXY_wwwwwx-qQQQRRSSS"
username="gusbemacbe"
2. I used a declaration for multiple files:
declare -a context_dirs=(
"home/.config/Code - Insiders/Preferences"
"home/.config/Code - Insiders/languagepacks.json"
"home/.config/Code - Insiders/rapid_render.json"
"home/.config/Code - Insiders/storage.json"
)
3. I used the condition for
loop with jq
to convert all files from the declaration context_dirs
to encoded URLs:
for urlencode in "${context_dirs[@]}"; do
paths=$(jq -nr --arg v "$urlencode" '$v|@uri')
done
4. I used the condition for
loop to download with curl
multiple files taken from paths
converted by jq
. It is important that I used -0
and -J
to output the file name, and -H
for "PRIVATE-TOKEN: $private_token"
:
for file in "${paths[@]}"; do
curl -sLOJH "PRIVATE-TOKEN: $private_token" "https://gitlab.com/api/v4/projects/$username%2F$repo/repository/files/$file/raw?ref=$branch "
done
Complete source code:
branch="master"
id="1911000X"
repo="my-dotfiles"
private_token="XXY_wwwwwx-qQQQRRSSS"
username="gusbemacbe"
declare -a context_dirs=(
"home/.config/Code - Insiders/Preferences"
"home/.config/Code - Insiders/languagepacks.json"
"home/.config/Code - Insiders/rapid_render.json"
"home/.config/Code - Insiders/storage.json"
)
for urlencode in "${context_dirs[@]}"; do
paths=$(jq -nr --arg v "$urlencode" '$v|@uri')
done
for file in "${paths[@]}"; do
curl -sLOJH "PRIVATE-TOKEN: $private_token" "https://gitlab.com/api/v4/projects/$username%2F$repo/repository/files/$file/raw?ref=$branch "
done
But the two conditions for
loop output only an encoded path and downloaded only a file.
Oo'-
(255 rep)
Jun 1, 2020, 06:20 AM
• Last activity: Jun 1, 2020, 06:50 AM
5
votes
1
answers
673
views
Declare command and shell expansion
I stumbled by accident on the following `bash` behaviour, which is for me kind of unexpected. # The following works $ declare bar=Hello # Line 1 $ declare -p bar # Line 2 declare -- bar="Hello" $ foo=bar # Line 3 $ declare ${foo}=Bye # Line 4 $ declare -p bar # Line 5 declare -- bar="Bye" # The foll...
I stumbled by accident on the following
bash
behaviour, which is for me kind of unexpected.
# The following works
$ declare bar=Hello # Line 1
$ declare -p bar # Line 2
declare -- bar="Hello"
$ foo=bar # Line 3
$ declare ${foo}=Bye # Line 4
$ declare -p bar # Line 5
declare -- bar="Bye"
# The following fails, though
$ declare -a array=( A B C ) # Line 6
$ declare -p array # Line 7
declare -a array=(="A" ="B" ="C")
$ foo=array # Line 8
$ declare -a ${foo}=(="A" ="XXX" ="C") # Line 9
bash: syntax error near unexpected token ('
# Quoting the assignment fixes the problem
$ declare -a "${foo}=(A YYY C)" # Line 10
$ declare -p array # Line 11
declare -a array=(="A" ="YYY" ="C")
Since shell expansion
1. Brace expansion
2.
* Tilde expansion
* Parameter and variable expansion
* Arithmetic expansion
* Process substitution
* Command substitution
3. Word splitting
4. Filename expansion
is performed on the command line after it has been split into tokens (followed by quote removal) but before the final command is executed, I would not have expected line 9 to fail.
**Which is the rationale behind it, that makes bash
not accept line 9?** Or, said differently, **what am I missing in the way line 9 is processed by bash
that makes it fail but makes line 10 succeed?**
In any case, quoting is not always going to straightforwardly work and it would require extra attention in case the array elements are strings with e.g. spaces.
Axel Krypton
(336 rep)
Mar 16, 2020, 09:46 AM
• Last activity: Mar 16, 2020, 08:26 PM
0
votes
1
answers
996
views
Reading variable from a txt file using bash
I'm new to bash. I'm trying to write a script that will read data from a text find and declare some variables. In the example below we read from a tab delimited file "ab.txt" that looks like this: a->AA b->BB Where -> denotes a tab. I'm reading this data with this code: ``` #!/bin/bash while read li...
I'm new to bash.
I'm trying to write a script that will read data from a text find and declare some variables. In the example below we read from a tab delimited file "ab.txt" that looks like this:
a->AA
b->BB
Where -> denotes a tab.
I'm reading this data with this code:
#!/bin/bash
while read line
do
tmp=(${line///})
fieldName=${tmp}
case $fieldName in
"a")
a=${tmp}
;;
"b")
b=${tmp}
;;
esac
done < "ab.txt"
echo "a:"
echo $a
echo "b:"
echo $b
echo "concat a,b"
echo $a$b
echo "concat b,a"
echo $b$a
This gives me "a" and "b" nicely, but will not concatenate a and b!
The output is this:
a:
AA
b:
BB
concat a,b
BB
concat b,a
AA
What am I doing wrong?
Adi Ro
(101 rep)
Jan 8, 2020, 07:04 PM
• Last activity: Jan 9, 2020, 08:16 AM
4
votes
1
answers
1464
views
How to read keyboard input and assign it to a local variable?
I have this very simple script: #!/bin/bash read local _test echo "_test: $_test" This is the output. $ ./jltest.sh sdfsdfs _test: I want the variable `_test` to be local only. Is this possible?
I have this very simple script:
#!/bin/bash
read local _test
echo "_test: $_test"
This is the output.
$ ./jltest.sh
sdfsdfs
_test:
I want the variable
_test
to be local only. Is this possible?
mrjayviper
(2253 rep)
Nov 12, 2019, 02:51 PM
• Last activity: Nov 12, 2019, 03:20 PM
6
votes
2
answers
4701
views
What is a variable attribute?
I aim to understand the general concept of "variable attributes" hoping it will help me understand [what is declare in Bash][1]. What is a variable attribute? Why would someone want to give an attribute to a variable? Why isn't just creating an variables and expanding them in execution be "enough" w...
I aim to understand the general concept of "variable attributes" hoping it will help me understand what is declare in Bash .
What is a variable attribute? Why would someone want to give an attribute to a variable? Why isn't just creating an variables and expanding them in execution be "enough" when working with variables?
user149572
Jun 1, 2019, 06:01 PM
• Last activity: Jun 2, 2019, 06:57 PM
9
votes
1
answers
4671
views
Does `declare -a A` create an empty array `A` in Bash?
Does `declare -a A` create an empty array `A` in bash, or does it just set an attribute in case `A` is assigned to later? Consider this code: set -u declare -a A echo ${#A[*]} echo ${A[*]} A=() echo ${#A[*]} echo ${A[*]} A=(1 2) echo ${#A[*]} echo ${A[*]} What should be the expected output? In Bash...
Does
declare -a A
create an empty array A
in bash, or does it just set an attribute in case A
is assigned to later?
Consider this code:
set -u
declare -a A
echo ${#A[*]}
echo ${A[*]}
A=()
echo ${#A[*]}
echo ${A[*]}
A=(1 2)
echo ${#A[*]}
echo ${A[*]}
What should be the expected output?
In Bash 4.3.48(1) I get bash: A: unbound variable
when querying the number of elements after declare
.
I also get that error when accessing all the elements.
I know that later versions of Bash treat this differently.
Still I'd like to know whether declare
actually *defines* a variable (to be empty).
U. Windl
(1715 rep)
May 28, 2019, 10:42 AM
• Last activity: May 28, 2019, 12:01 PM
4
votes
3
answers
4240
views
Function to conditionally set a variable read-only
If I had a script which sets variables read-only to some odd values, and sets `errexit` because of other unsafe operations: #!/bin/bash set -e declare -r NOTIFY=$(case "$OS" in (macosx) echo macos_notify ;; (linux) echo linux_notify ;; (*) echo : ;; esac) declare -r SAY=_say # _say is a function dec...
If I had a script which sets variables read-only to some odd values, and sets
errexit
because of other unsafe operations:
#!/bin/bash
set -e
declare -r NOTIFY=$(case "$OS" in (macosx) echo macos_notify ;; (linux) echo linux_notify ;; (*) echo : ;; esac)
declare -r SAY=_say # _say is a function
declare -r VERSION=0.99
set +e
And I source it to get the definitions, the second time because it's in development:
$ . s.bash
$ . s.bash
bash: declare: NOTIFY: readonly variable
Exited
Normally declare -r EXISTING_VAR
would neither stop the script nor remove the old, working definition of EXISTING_VAR
.
But with errexit
, assigning to an existing variable is understandably a failure. The easy options are to remove -r
or use set +e
for that part of the script.
Barring those, **is it possible to write a Bash function to take the place of declare -r
but not re-assign if the name already exists**?
I tried:
# arg #1: var name, #2: value
set_var_once () {
# test whether the variable with the
# name stored in $1 exists
if [[ -z "${!1}" ]]
then # if it doesn't, set it
declare -r $1=$2
fi
}
I also tried things along the lines of eval "declare -r $1=$(eval $2)"
, it feels like eval
is required somewhere here but I'm not sure where.
All of the versions of set_var_once
result in not setting the variable they should.
cat
(3538 rep)
Oct 29, 2018, 07:52 PM
• Last activity: Apr 16, 2019, 02:22 PM
0
votes
1
answers
83
views
Parse 3rd entry in declare result
I have this: > cd 31 > /Users/alexamil/WebstormProjects/oresoftware/botch/botch-shell-overrides.sh the above style output, is given by this command: declare -F my_bash_func How can I grab just the file name from that result? something like: file=$(declare -F my_bash_func | grab_3rd_entry) __________...
I have this:
> cd 31
> /Users/alexamil/WebstormProjects/oresoftware/botch/botch-shell-overrides.sh
the above style output, is given by this command:
declare -F my_bash_func
How can I grab just the file name from that result? something like:
file=$(declare -F my_bash_func | grab_3rd_entry)
_______________
I have to use:
shopt -s extdebug
declare -F my_bash_func
shopt -u extdebug
but this doesn't work on MacOS:
shopt -s extdebug
declare -pf my_bash_func
shopt -u extdebug
the latter yields a weird error:
> declare: my_bash_func: not found
but using declare -F can find the function, so not sure why the
-pf
option doesn't work.
Alexander Mills
(10734 rep)
May 2, 2018, 04:36 AM
• Last activity: May 2, 2018, 06:02 AM
Showing page 1 of 17 total questions