How can i change directory in shell script with variables - shell

this script file name "1sr" and i can work in terminal ". 1sr"
i want to change directory "home/byram/workspace/1/src/com/seri/*"
#!bin/sh
f=$(basename $0 | tr -d "sr")
pth="/home/byram/workspace/$f"
my1=$(ls $pth/src/com/seri)
cd $etc/src/com/seri/$my1
after ". 1sr" command f variable set "bash"
how can i fix it?

I would suggest a function called "prj" to put in your .bashrc:
prj () {
cd /home/byram/workspace/"$1"/src/com/seri
}
Then use it like this
prj 1 # Switch to ...1/src/com/seri
prj 2 # Switch to ...2/src/com/seri

i add in .bashrc this lines:
wr (){
cd /home/byram/workspace/"$1"/w
v1=$(ls /home/byram/workspace/"$1"/src/*/*)
v2=$(ls /home/byram/workspace/"$1"/src/*)
v3=$(ls /home/byram/workspace/"$1"/src/)
echo "$v3.$v2.$v1"
}
works for any project eg. com.example.abc,org.samp.xyz
thanks for #chepner

Related

Why is this something does Bash say that modavar command even tho i aliased it

Note this is sourced, so this is not a shell script.
I am not asking for how to enable alias in noninteractive shell. I did this: shopt -s expand_aliases.
The Bash version is 5.1.4.
How to recreate:
Create a file named "p":
linky(){
comdll="cat"
shopt -s expand_aliases
alias modavar="$comdll"
echo "$argin" | modavar #| getlinks "$argin" | sort -u
}
Then run
echo "source p ; linky https://duckduckgo.com" | bash --norc
Expected output:
https://duckduckgo.com
Actual output:
p: line 5: modavar: command not found
When I run this once it give me
linky(){ alias jkl=echo\ hel; jkl; }
linky
bash: jkl: command not found
But if I do this,
linky(){ alias jkl=echo\ hel; jkl; }
linky
linky(){ alias jkl=echo\ hel; jkl; }
linky
It gives me
hel
What is happening?
You can't define the alias inside a function and use it there. Consider these examples:
alias foo=cat
ffoo() {
echo abc|foo
}
fbar() {
alias bar=cat
echo abc|bar
}
ffoo #->prints abc
fbar #->prints command not found

Calling Shell-methods by chain of files in subdirectories

I'm trying to call methods from file to file with structure like:
/root
/subDir
/subSubDir
inSubSub.sh
inSub.sh
inRoot.sh
Files contents:
inRoot.sh:
#!/bin/bash
source ./subDir/inSub.sh
subMethod;
inSub.sh:
#!/bin/bash
source ./subSubDir/inSubSub.sh
subMethod () {
echo "I'm in sub"
}
subSubMethod;
inSubSub.sh:
#!/bin/bash
subSubMethod () {
echo "I'm in subSub"
}
subSubMethod;
Result of running $ ./inRoot.sh
subDir/inSub.sh: line 2: subSubDir/inSubSub.sh: No such file or directory
subDir/inSub.sh: line 6: subSubMethod: command not found
I'm in sub
So, it works for the first call but doesn't work deeper.
btw: using . ./ instead of source ./ returns the same
How to do it right, if it's possible?
You must change your inSub.sh like that
cat ./subDir/inSub.sh
#!/bin/bash
var="${BASH_SOURCE[0]}"
source "${var%/*}"/subSubDir/inSubSub.sh
subMethod () {
echo "I'm in sub"
}
subSubMethod;

How to alias an export in bash

I am trying to set an env variable which I can use to do relative directory chains. I am trying to do it the following way but cant get it to work. How do I do it?
alias sroot="export SROOT="$PWD""
alias drumit="cd $SROOT/abc/def/drumit"
If I type sroot, it takes the alias but when i type drumit, it gives me an error saying
bash: cd: /abc/def/drumit: No such file or directory
Looks like when the shell was launched it takes $SROOT as .
Appreciate any help.
Thanks
Your $PWD and $SROOT variables are being expanded at the time you define the aliases, not when you are using them. Put a \ in front of them to escape them while they are defined.
alias sroot="export SROOT="\$PWD""
alias drumit="cd \$SROOT/abc/def/drumit"
When you initially set the alias, it expands $PWD instead of keeping it as the variable form. Try using function instead like this:
$ function sroot {
> export SROOT="$PWD"
> }
$ export -f sroot
$ function drumit {
> cd $SROOT/cron
> }
$ export -f drumit
$ declare -f sroot
sroot()
{
export SROOT="$PWD"
}
$ declare -f drumit
drumit ()
{
cd $SROOT/abc/def/drumit
}
This is what is currently happening when you alias like in your question (variable expanding):
$ alias sroot="export SROOT="$PWD""
$ alias drumit="cd $SROOT/abc/def/drumit"
$ alias
alias SROOT='/home/jon'
alias drumit='cd /home/jon/abc/def/drumit'
alias sroot='export SROOT=/home/jon'
Escaping would work too:
$ alias sroot="export SROOT="\$PWD""
$ alias drumit="cd \$SROOT/abc/def/drumit"
$ alias
alias drumit='cd $SROOT/abc/def/drumit'
alias sroot='export SROOT=$PWD'

How to add/use a variable to my bashrc file?

I'm a newbie to Linux operating system
I need to do the following:-
I have multiple projects under "~/myprojects"
Think of like >ls ~/myprojects
project1 project2i newproject project_possible....
All my projects have a fixed structure see as below:-
ls ~/myprojects/
src lib inc common test_scripts
(all these are directories having some files in them
For navigating the current()
I want to do something like this in my bashrc file.
assign curr_project = "$1"
alias psrc='cd ~/myprojects/curr_project/src/'
alias plib='cd ~/myprojects/curr_project/lib/'
Thanks in advance
You can use an environment variable to specify the current project and use the variable in your aliases:
current() {
export CURR_PROJECT=$1
}
alias psrc='cd ~/myprojects/$CURR_PROJECT/src/'
alias plib='cd ~/myprojects/$CURR_PROJECT/lib/'
First you set the CURR_PROJECT by using
$ current project1
Then you call your alias to change directories:
$ psrc
Hope that helps.
I use something similar for my work environment - many projects with a common directory structures. I also use a selector to allow me choose projects quickly without typing their name. You may find it useful.
E.g.
current()
{
export PROJECT_ROOT=~/myprojects
# If you pass a project name, use it, otherwise print a list
# for the user to select
if [ -n "$1" ]; then
export CURRENT_PROJECT=$1
else
# Find subdirectories in PROJECT_ROOT
SUBDIRS=`find $PROJECT_ROOT -mindepth 1 -maxdepth 1 -type d -printf "%f "`
if [ -n "$SUBDIRS" ]; then
PS3="Select project: "
select d in $SUBDIRS; do
if [[ -n $d ]]; then
export CURRENT_PROJECT=$d
break
else
echo "Bad choice"
return
fi
done
else
echo "No projects found"
return
fi
fi
# Now we have the CURRENT_PROJECT name, set up the aliases
alias psrc='cd $PROJECT_ROOT/$CURRENT_PROJECT/src/'
alias plib='cd $PROJECT_ROOT/$CURRENT_PROJECT/lib/'
}
Then if you type "current", you will get a choice:
~$ current
1) proj1
2) proj2
3) proj3
Select project:
This is a real time-saver for me - maybe it will be for you too.

Run a string as a command within a Bash script

I have a Bash script that builds a string to run as a command
Script:
#! /bin/bash
matchdir="/home/joao/robocup/runner_workdir/matches/testmatch/"
teamAComm="`pwd`/a.sh"
teamBComm="`pwd`/b.sh"
include="`pwd`/server_official.conf"
serverbin='/usr/local/bin/rcssserver'
cd $matchdir
illcommando="$serverbin include='$include' server::team_l_start = '${teamAComm}' server::team_r_start = '${teamBComm}' CSVSaver::save='true' CSVSaver::filename = 'out.csv'"
echo "running: $illcommando"
# $illcommando > server-output.log 2> server-error.log
$illcommando
which does not seem to supply the arguments correctly to the $serverbin.
Script output:
running: /usr/local/bin/rcssserver include='/home/joao/robocup/runner_workdir/server_official.conf' server::team_l_start = '/home/joao/robocup/runner_workdir/a.sh' server::team_r_start = '/home/joao/robocup/runner_workdir/b.sh' CSVSaver::save='true' CSVSaver::filename = 'out.csv'
rcssserver-14.0.1
Copyright (C) 1995, 1996, 1997, 1998, 1999 Electrotechnical Laboratory.
2000 - 2009 RoboCup Soccer Simulator Maintenance Group.
Usage: /usr/local/bin/rcssserver [[-[-]]namespace::option=value]
[[-[-]][namespace::]help]
[[-[-]]include=file]
Options:
help
display generic help
include=file
parse the specified configuration file. Configuration files
have the same format as the command line options. The
configuration file specified will be parsed before all
subsequent options.
server::help
display detailed help for the "server" module
player::help
display detailed help for the "player" module
CSVSaver::help
display detailed help for the "CSVSaver" module
CSVSaver Options:
CSVSaver::save=<on|off|true|false|1|0|>
If save is on/true, then the saver will attempt to save the
results to the database. Otherwise it will do nothing.
current value: false
CSVSaver::filename='<STRING>'
The file to save the results to. If this file does not
exist it will be created. If the file does exist, the results
will be appended to the end.
current value: 'out.csv'
if I just paste the command /usr/local/bin/rcssserver include='/home/joao/robocup/runner_workdir/server_official.conf' server::team_l_start = '/home/joao/robocup/runner_workdir/a.sh' server::team_r_start = '/home/joao/robocup/runner_workdir/b.sh' CSVSaver::save='true' CSVSaver::filename = 'out.csv' (in the output after "runnning: ") it works fine.
You can use eval to execute a string:
eval $illcommando
your_command_string="..."
output=$(eval "$your_command_string")
echo "$output"
I usually place commands in parentheses $(commandStr), if that doesn't help I find bash debug mode great, run the script as bash -x script
don't put your commands in variables, just run it
matchdir="/home/joao/robocup/runner_workdir/matches/testmatch/"
PWD=$(pwd)
teamAComm="$PWD/a.sh"
teamBComm="$PWD/b.sh"
include="$PWD/server_official.conf"
serverbin='/usr/local/bin/rcssserver'
cd $matchdir
$serverbin include=$include server::team_l_start = ${teamAComm} server::team_r_start=${teamBComm} CSVSaver::save='true' CSVSaver::filename = 'out.csv'
./me casts raise_dead()
I was looking for something like this, but I also needed to reuse the same string minus two parameters so I ended up with something like:
my_exe ()
{
mysql -sN -e "select $1 from heat.stack where heat.stack.name=\"$2\";"
}
This is something I use to monitor openstack heat stack creation. In this case I expect two conditions, an action 'CREATE' and a status 'COMPLETE' on a stack named "Somestack"
To get those variables I can do something like:
ACTION=$(my_exe action Somestack)
STATUS=$(my_exe status Somestack)
if [[ "$ACTION" == "CREATE" ]] && [[ "$STATUS" == "COMPLETE" ]]
...
Here is my gradle build script that executes strings stored in heredocs:
current_directory=$( realpath "." )
GENERATED=${current_directory}/"GENERATED"
build_gradle=$( realpath build.gradle )
## touch because .gitignore ignores this folder:
touch $GENERATED
COPY_BUILD_FILE=$( cat <<COPY_BUILD_FILE_HEREDOC
cp
$build_gradle
$GENERATED/build.gradle
COPY_BUILD_FILE_HEREDOC
)
$COPY_BUILD_FILE
GRADLE_COMMAND=$( cat <<GRADLE_COMMAND_HEREDOC
gradle run
--build-file
$GENERATED/build.gradle
--gradle-user-home
$GENERATED
--no-daemon
GRADLE_COMMAND_HEREDOC
)
$GRADLE_COMMAND
The lone ")" are kind of ugly. But I have no clue how to fix that asthetic aspect.
To see all commands that are being executed by the script, add the -x flag to your shabang line, and execute the command normally:
#! /bin/bash -x
matchdir="/home/joao/robocup/runner_workdir/matches/testmatch/"
teamAComm="`pwd`/a.sh"
teamBComm="`pwd`/b.sh"
include="`pwd`/server_official.conf"
serverbin='/usr/local/bin/rcssserver'
cd $matchdir
$serverbin include="$include" server::team_l_start="${teamAComm}" server::team_r_start="${teamBComm}" CSVSaver::save='true' CSVSaver::filename='out.csv'
Then if you sometimes want to ignore the debug output, redirect stderr somewhere.
For me echo XYZ_20200824.zip | grep -Eo '[[:digit:]]{4}[[:digit:]]{2}[[:digit:]]{2}'
was working fine but unable to store output of command into variable.
I had same issue I tried eval but didn't got output.
Here is answer for my problem:
cmd=$(echo XYZ_20200824.zip | grep -Eo '[[:digit:]]{4}[[:digit:]]{2}[[:digit:]]{2}')
echo $cmd
My output is now 20200824

Resources