w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
What is "variable scope"? Variables have a limited "scope", or "places from which they are accessible". Just because you wrote $foo = 'bar'; once somewhere in your application doesn't mean you can refer to $foo from everywhere else inside the application. The variable $foo has a certain scope within which it is valid and only code in the same scope has access to the variable. How is a scope defined in PHP? Very simple: PHP has function scope. That's the only kind of scope separator that exists in PHP. Variables inside a function are only available inside that function. Variables outside of functions are available anywhere outside of functions, but not inside any function. This means there's one special scope in PHP: the global scope. Any variable declared outside of any function is with

Categories : PHP

How do I use variable names using a for loop to reference a number in the variable name?
Use this $e = ${'_SESSION_Job10'.$x}; // $e = $_SESSION_Job101; actual variable here Live Demo instead of $e = '$_SESSION_Job10'.$x; // $e = '$_SESSION_Job101'; // string here Edit You have to use array like this ${'_SESSION_Job10'.$x}['progress']; Demo

Categories : PHP

how to assign a variable value to another variable instead of reference dojo javascript
You need to either do a deep clone of requiredStore (going through properties and prototype to create a perfect duplicate), or else just create a different memory store altogether: requiredStore = new Memory({ data:res }); temporaryStore = new Memory({ data: res }); I don't know why you wouldn't use this approach, but if you want to do a deep clone this question will help: Most efficient way to clone an object?

Categories : Javascript

bash expand variable in a variable, with $ as prefix
The more idiomatic way of iterating over the positional parameters is to use $@: for p in "$@"; do GET_BLOCK "/$p/" done What you wanted was for ((i=1; i<$#; i++)) do GET_BLOCK "/${!i}" done but this is both non-standard and less clear than iterating over $@ directly.

Categories : Bash

Bash: update variable that uses a updated variable
Instead of a string, you should use a shell function: function startecho() { date +%F_%T ; echo " dobackup.sh | Backup $bc started!" ; } function endecho() { date +%F_%T ; echo " dobackup.sh | Backup $bc ended!" ; } startecho endecho bc=$((bc+1)) startecho endecho

Categories : Bash

In bash, how to use a variable as part of the name of another variable?
You can use eval: #!/bin/bash array_0=(1 2 3) array_1=(4 5 6) array_2=(7 8 9) for a in {0..2} ; do for i in {0..2} ; do eval 'echo ${'"array_$a[$i]"'}' done done Vaughn Cato's syntax is slightly more verbose, but the echo statement itself is more decipherable. You replace the inner part of the double for loop with these two lines: array_a=array_$a[$i] echo ${!array_a}

Categories : Bash

How to tell if a JavaScript variable is a reference to another variable
var foo = {'some': 'object'}; var bar = foo; After this, foo and bar are exactly the same as in "they both point to the same object". But besides that there is no relationship between foo and bar, so bar is not a reference to foo but to the same object. So the answer is "no" since JavaScript does not have references to other variables. However, to check for circular dependencies - which is what you actually need/want in your example - there are various other, more appropriate, solutions available this question: Is there a way to test circular reference in JavaScript? Additionally, native JSON encoding using JSON.stringify() already checks for this: >>> var obj = {}; >>> obj.x = obj; >>> JSON.stringify(foo) TypeError: cyclic object value

Categories : Javascript

Syntax Help - variable reference within variable
array_push($array, $_POST['miles'.$i.'1']); actually needs to be array_push($array, $_POST['miles1'.$i]); after looking at my $_POST again

Categories : PHP

BASH: how to define an array as environment variable before calling a bash script
Incredibility weird.... I have never seen that before. It looks like the array is not passed to the subshell. One way around this is to source the script instead of executing it: declare -a MYARR=( 1 2 ); . ./myscript.sh

Categories : Arrays

Run a bash including a variable in the "bash XXX.sh" command
You can take advantage of shell parameter expansion to smoothly read variables from the environment of the parent process, if it's that what you want to achieve. Look at the following script named test.sh: #!/bin/bash VARIABLE=${VARIABLE:="default value"} echo $VARIABLE If you start it with the line $ ./test.sh it outputs default value But if you invoke test.sh with the line $ VARIABLE="custom Value" ./test.sh it outputs custom value But make sure that the variable assignment is at the beginning of the line. Otherwise it is passed to test.sh as command line argument. The used form of parameter expansion ${parameter:=word} is described in the bash reference manual as: If parameter is unset or null, the expansion of word is assigned to parameter. The value of param

Categories : Bash

"Undefined reference" error when passing variable by reference
It looks like you are missing the X11 library for linking. add -lX11 to the g++ invocation. This provides the steps required. Right click on Project Folder> Properties> C/C++ Build > Settings > GCC C++ Linker > Libraries > add "X11"

Categories : C++

Declare a variable as a reference with function that returns a reference
In this version vector<float>& myNewVar = myfunction(); myNewVar is a reference to whatever myfunction() returns a reference to. In this one vector<float> myNewVar = myfunction(); myNewVar is a copy of whatever myfunction() returns a reference to. It takes the reference as input to std::vector<float>'s copy constructor. Perhaps this is illustrated better without a function: int i = 42; // I want a referennce, so I create one int& j = i; // I want a copy, so I make one, even though j is a reference. // j is just an alias for i, so k really is a copy of i. int k = j;

Categories : C++

AS3 Advanced Variable Usage - Retrieve Value In Variable Selected Based On Value In Another Variable
Generally not a fan of having data-defining element names in XML, but - assuming event.dat is actually an XML object, and not an arbitrary object that you've manually parsed the XML into (can't tell from the question) - this is really a question about ECMAScript for XML (E4X) rather than variables in general. If so, this should work: for each (var menuField:XML in event.dat.child(mnVariable).element) { // Do something } Can't test at the moment, but this may also work (it's part of E4X standard, but not sure if Adobe implemented it): // Note, no dot before the indexer: for each (var menuField:XML in event.dat[mnVariable].element) { // Do something } The latter is also generally the way to access a property of an object using a string property name, so if event.dat is an arbitr

Categories : Actionscript

Jquery How to use .click() to update a variable and pass that variable to an array or add it to another variable
In this case the alert will show undefined since it is executed before the actual click happens. But the value of v1PackCharge is globally set, you can use it outside the click handler. Only thing is you need to modify the test case Demo: Fiddle

Categories : Jquery

^H in bash variable
The backspace just moves the cursor one position to the right without actually erasing what's printed on the screen. Only your second instruction actually erases the 4th character by overwriting it with the trailing space in your string. I'll try to visualize it: $ echo "hello^H^H" hello ^ `-- cursor position $ echo "hello^H^H " hel o ^ `-- cursor position

Categories : Bash

Failure of Bash $@ variable
You need to double-quote the $@to keep bash from performing the unwanted parsing steps (word splitting etc) after substituting the argument values: function Foobar { cmd -opt1 -opt2 "$@" } EDIT from the Special Parameters section of the bash manpage: @ Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "$1" "$2" ... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the begin- ning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, "$@" and $@ e

Categories : Bash

search variable and corresponding value in bash
All together: $ data=$(grep -nPo '(?<=delay=)d+' file | sort -rn -t: -k2 | head -1) $ line=${data%%:*} $ delay=${data##*:} $ awk -v line=$line -v delay=$delay 'NR==line {print "longest delay was **", delay, "** on", $1, $2, "at", $3, "at server",$4, " ",$0}' file longest delay was ** 162708 ** on Jul 16 at 00:01:43 at server abc Jul 16 00:01:43 abc postfix/smtp[28815]: F19Dwq003: to=<sullcrom@em1.SulivanCromwell.com>, relay=em1.SullivanCromwell.com[223.222.222.2]:25, delay=162708, delays=162705/0.3/1.6/0.62, dsn=4.2.2, status=deferred (host em1.SullivanCromwell.com[223.222.222.2] said: 452 4.2.2 Mailbox full (in reply to RCPT TO command)) Explanation (spoiler: it can be boring) You can firstly get the following: $ grep -nPo '(?<=delay=)d+' file | sort -rn -t: -k2 3:16

Categories : Bash

How to get expect to set a bash variable
I don't know Expect, but I think it's something like this SSH_SUCCESS=$(expect <<EOF ... expect { "0" { puts "PASSED" } "1" { puts "FAILED" } ... EOF ) echo $SSH_SUCCESS

Categories : Bash

How to grep using a variable in bash
You should quote it grep "$GTUNNELNATNETIP" iptables2.out Read more about quoting variables in bash This must work. I cannot reproduce your trailing backslash error, but most probably you have some garbage in $GTUNNELNATNETIP variable

Categories : Regex

how to set file as a variable in bash
If you know there are exactly 14 files, do this: for i in {1..14}; do clustalo -i home/my_directory/$a.fasta -o home/my_directory/$b.aln done If you want to process all of the *.fasta files, however many there are, then do: for file in home/my_directory/*.fasta; do clustalo -i "$file" -o "${file%.fasta}.aln" done To understand this, ${file%.fasta} gives us $file with the .fasta extension stripped off. If you want to store the file names in a variable first, the best thing to do is to use an array variable. You do that by adding parentheses around the variable assignment, and then accessing the array values with the strange syntax "${array[@]}". files=(home/my_directory/*.fasta) for file in "${files[@]}"; do clustalo -i "$file" -o "${file%.fasta}.aln" done

Categories : Bash

How do i populate this variable in bash?
To prevent substitution, you can use either single-quotes '...' or a backslash ; for example, this command: echo '$foo' $foo "$foo" will print this: $foo $foo $foo and will not use the variable foo. In your case, rather than using "..." for the whole argument, you probably should use '...' everywhere except where you specifically need substitution. So: HOST=foo DIR=bar ssh user@$HOST ' function test { CURHOST='"$HOST"' cd $DIR mkdir -p $CURHOST }; test'

Categories : Bash

BASH: sed -e not allowing my variable
Just use awk, it has less caveats linenumber=$(awk -v p="$player" '$0 ~ p { print NR }' "$outputfile") awk -v n="$linenumber" 'NR == n { sub(/2013-08-25/,"test") }1' "$outputfile" and of course you don't need multiple steps: awk -v p="$player" '$0 ~ p{ sub(/2013-08-25/,"test") }1' "$outputfile" To write the output back to your input file: awk 'script' "$outputfile" > tmp && mv tmp "$outputfile" The above does the same thing sed does, it's just that you specify the tmp file instead of sed coming up with one for you. If you'd rather have awk do that for you then with recent gawk versions you can do: awk -i inedit 'script' "$outputfile" Whatever. It is NOT worth giving up awk simplicity and functionality to avoid the triviality of creating your own tmp file.

Categories : Bash

Is it possible to use a variable in for syntax in bash?
It is not possible to use variables in the {N..M} syntax. Instead, what you can do is use seq: $ var=5 $ for i in $(seq 1 $var) ; do echo "$i"; done 1 2 3 4 5 Or... $ start=3 $ end=8 $ for i in $(seq $start $end) ; do echo $i; done 3 4 5 6 7 8

Categories : Bash

How to copy local variable to global variable if both have the same names in C without using a third variable?
What you're doing is "shadowing" the global variable. In order to unshadow it in a local block, declare it in its own nested block with extern. void myFunction() { int myVariable { extern int myVarible; //modify myVariable global here; } //modify myVariable localhere }

Categories : C

two layers of quotes around a bash variable
echo "loadings_file <- '$loadings' ; calls_file <- '$file'" If you specifically need double quoting: echo "loadings_file <- "$loadings" ; calls_file <- "$file""

Categories : R

Select random variable in Bash
Or use an array: #!/bin/bash NUMBER=$(( $RANDOM % 9 )) echo $NUMBER COLOURS=(AliceBlue AntiqueWhite AntiqueWhite1 AntiqueWhite2 AntiqueWhite3 AntiqueWhite4 BlanchedAlmond BlueViolet CadetBlue) echo ${COLOURS[$NUMBER]}

Categories : Bash

bash - SQL Query Outputs to variable
Taken from bash script - select from database into variable, you can read the query result into a variable. Example mysql> SELECT * FROM domains; +-------+---------+ | user | domain | +-------+---------+ | user1 | domain1 | | user2 | domain2 | | user3 | domain3 | +-------+---------+ Usage $ myvar=$(mysql -D$MYDB -u$MYUSER -p$MYPASS -se "SELECT domain FROM domains") $ echo $myvar domain1 domain2 domain3 echo is the bash command for output. You can then split $myvar into separate variables: $ read var1 var2 var3 <<< $myvar $ echo $var1 domain1 $ echo $var2 domain2 You can combine these two commands into a single one: read var1 var2 var3 <<< $(mysql -D$MYDB -u$MYUSER -p$MYPASS -se "SELECT domain FROM domains") It is possible to store the results into arrays

Categories : Mysql

BASH - how can i get the variable value inside the EOF tags?
Remove the backslash before EOF: #!/bin/bash i=ok # This prints "Bwah ok" cat <<EOF Bwah $i EOF # This prints "Bwah $i" cat <<EOF Bwah $i EOF To get your last line display rightsubnet="10.109.0.20/32" (for i=1), you need something like this: i=1 val1=beep val2=bop rightval="val$i" cat <<EOF This is a beep: ${!rightval} EOF That is, you compute the name of the variable you want, put that in another variable, and use the ${!var} syntax. But for that kind of thing you should rather use an array: i=0 vals=(beep bop) cat <<EOF This is a beep: ${vals[$i]} EOF Note however that the indexes start at 0.

Categories : Linux

call a bash variable which has spaces
grep isn't going to see that you're passing it a shell variable. Shells expand/replace their variables before firing up the requested program. so grep thinks it's being invoked as ... | grep trunk-index FOR in footer | ... and end up searching for the phrase trunk-index in some non-existent files FOR,in, and footer. Try ... | grep '$grepper' | ... instead.

Categories : Bash

In bash How do I echo out a $ without reading it as a variable?
Wherever you have $VAR, replace it with $VAR. In a nutshell, is an escape character that will 'ignore' special characters following it. So in your case, use $item.

Categories : Bash

What do the characters in the bash environment variable $- mean ?
From man bash: - Expands to the current option flags as specified upon invocation, by the set builtin command, or those set by the shell itself (such as the -i option). So these are the current options that control the behavior of the shell. In particular: h: Cache location of binaries in the $PATH. Speeds up execution, but fails if you move binaries around during the shell session. i: The current shell is interactive m: Job control is enabled B: Brace expansion is enabled H: History substitution like !-1

Categories : Linux

Iterating over variable name in bash script
You can use array: train[1]=path/to/first/file train[2]=path/to/second/file ... train[20]=path/to/third/file for i in {1..20} do python something.py ${train[$i]} done Or eval, but it awfull way: train1=path/to/first/file train2=path/to/second/file ... train20=path/to/third/file for i in {1..20} do eval "python something.py $train$i" done

Categories : Bash

Git Branch Bash Variable Shortcut
Which branch you are on depends on which directory you are in. If you have two git work trees, ~/a and ~/b, then typing cd ~/a can put you on one branch and typing cd ~/b can put you on another branch. So trying to set $branch in your .bash_profile isn't going to work. You need to update $branch every time you change work trees, and after any command that can change the branch of the current work tree. The simplest thing to do is just not set a variable. Instead, make an alias: alias branch='git symbolic-ref --short -q HEAD 2>/dev/null' And then use it like this: git push origin $(branch) or like this if you're old-school: git push origin `branch` If you really want to set an environment variable, the simplest solution is to just set it every time you print your prompt: _

Categories : GIT

Create variable BASH command
A working script would look like this: # set propper default value top="" if [ -n "$2" ] then # use double quotes instead of back-tics # back-tics are for command substitution # but you need the command itself as a string top="| head -n $2" fi awk '{print $17, ">", $19;}' "$logs_folder$i" | sort -g | uniq -c | sort -r -g $top

Categories : Bash

Use part of filename as variable bash
You're grepping for the word contacts - which, depending on what else you have in those files, may always be present. Instead, use grep -q "^user.$NAME.Contacts" to look for your line.

Categories : Bash

How do I execute a command in a variable in bash?
In general you should not store redirections in a variable. And you should store commands in an array. cmd=(echo "hello world") log="somelogfile" "${cmd[@]}" >> "$log"

Categories : Bash

BASH - Refer to parameters using variable
How about this? #!/usr/bin/bash res=0 while [[ $# -gt 0 ]] do res=$(($res * 2 + $1)) shift done echo $res $ ./bin2dec 1 0 0 1 9 shift is a command that moves every parameter passed to the script to the left, decreasing it's value by 1, so that the value of $2 is now at $1 after a shift. You can actually a number with shift as well, to indicate how far to shift the variables, so shift is like shift 1, and shift 2 would give $1 the value that used to be at $3.

Categories : Bash

How to put a SELECT from Oracle into a bash variable?
You don't need to select into a variable and then use dbms_output.put_line to print it out. (Your select into statement won't work anyway, because you can't select multiple columns into a single data variable.) Instead, do it like this: data=$(sqlplus -S ${USER}/${PASSWORD} << EOF set head off set feedback off set pagesize 5000 set linesize 30000 select ACCESS_ID, PROFILE_ID, START_DATE, END_DATE, PLATFORM, ACCESS_TYPE, PERM_FLAG, ACTIVE_FLAG from uam.access_list where USER_ID='${USER_ID}'; exit EOF) echo "$data"

Categories : Oracle

Bash Shell: Cannot use variable $ as a path to run tar
~ doesn't expand to your home directory in double quotes. Just remove the double quotes: backup_source=~/momobobo backup_dest=~/momobobo_backup/ In cases where you have things you would want to quote, you can use ~/"momobobo"

Categories : Linux

Would like to take a Perl variable and pass it to bash
You can run all external programs and commands from Perl with system, exec and the backtick-operator (`` and qx()). Please refer to: http://perldoc.perl.org/functions/system.html http://perldoc.perl.org/perlop.html#%60STRING%60 http://perldoc.perl.org/functions/exec.html If you want to, say, copy stuff to another server, you can use the backticks like this: my $file = 'foo.csv'; `scp foo.csv someone@otherserver:dir/foo.csv`;

Categories : Perl



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.