BASH: How to copy a file without overwriting older files |
You can use the "--interactive" option (present in my cp from GNU coreutils
6.12) to prompt you before overwriting and fill it with a default:
echo 'n' | cp --interactive ~/somefile.txt ~/somefile_already_exists.txt
|
MacOS Terminal: how to use a seccond ssh key? |
The way to use several ssh keys is to use a ~/.ssh/config
Host serverKey1
Hostname server1 # or ip address of server1
User serverUser
IdentityFile ~/.ssh/id_rsa
Host serverKey2
Hostname server1 # or ip address of server1
User serverUser
IdentityFile ~/.ssh/id_rsa.gitlab
You then need to use an scp-syntax for your ssh url:
git clone serverKey1:/my/repo
git clone serverKey2:/my/repo
serverKey1 and serverKey2 are entries in your ~/.ssh/config file in order
to pass to ssh the right server, user and identify file (public and private
keys)
If those private keys are password-protected, you would still need to add
them.
You can see more at this atlassian help page: "Configure multiple SSH
identities for GitBash, Mac OSX, & Linux".
|
Pseudo-terminal will not be allocated because stdin is not a terminal ssh bash |
You seem to assume that when you run ssh to connect to a server, the rest
of the commands in the file are passed to the remote shell running in ssh.
They are not; instead they will be processed by the local shell once ssh
terminates and returns control to it.
To run remote commands through ssh there are a couple of things you can do:
Write the commands you want to execute to a file. Copy the file to the
remote server using scp, and execute it with ssh user@remote command
Learn a bit of TCL and use expect
Write the commands in a heredoc, but be careful with variable substitution:
substitution happens in the client, not on the server. For example this
will output your local home directory, not the remote:
ssh remote <<EOF
echo $HOME
EOF
To make it print the remote home directory
|
Start and stop logging terminal output to file from within bash script |
You can use the braces to redirect commands to tee through a pipe
#!/bin/bash
# to terminal and logfile.log
{
echo "aaa"
echo "bbb"
echo "ccc"
} 2>&1 | tee logfile.log
# only terminal
echo "ddd"
echo "eee"
|
is there a way to combine EOF with a terminal alias? |
Instead, create a function an save it in your ~/.bashrc:
importme()
{
ssh root@server.com << EOF
mysql
list databases;
EOF
}
Source (. ~/.bashrc) and you will be ready to use it with importme.
|
gnome-terminal new tab with alias as command to execute |
When a bash shell is started, per default bash executes the commands
specified in .bashrc. This is how your shell knows your alias's.
Now your idea does not work because gnome-terminal never sees your .bashrc
file.
You could try
gnome-terminal
--working-directory='<path-to-your-home-directory>/Desktop/myproject/
|
Bash alias autocompletion that considers only *.foo files |
Try:
complete -f -X '!*.tex' g
Then, you can type:
g <TAB>
And get the completions. Note: this doesn't complete directories. Someone
else may have a better solution using compgen.
There's a helpful autocomplete guide on The Linux Documentation Project
too.
|
alias .="cd .." causing bash to start at root |
. refers to the current directory, while .. refers to the one upper in the
dirs hierarchy.
What must be happening is that in your bashrc you have some . after this
alias definition, so it gets called and hence you are moved to the parent
directory.
So:
you enter and you are in /home/your_home
you set alias .="cd ..".
some dot . is found while reading .bashrc.
this dot is executed as to be an alias, so you get cd .., which moves you
to /home.
you probable have more than one . and it must get executed again, moving
you from /home to /.
Solution:
Create an alias with a better name that does not have any predefined
meaning.
Move your alias sourcing to the bottom of .bashrc.
|
How can one create and then use an alias in a function of a sourced Bash script? |
Note that aliases will have limited functionality for scripting. From the
Advanced Bash Scripting Guide:
In a script, aliases have very limited usefulness. It would be nice if
aliases could assume some of the functionality of the C preprocessor, such
as macro expansion, but unfortunately Bash does not expand arguments within
the alias body. [2] Moreover, a script fails to expand an alias itself
within "compound constructs," such as if/then statements, loops, and
functions. An added limitation is that an alias will not expand
recursively. Almost invariably, whatever we would like an alias to do could
be accomplished much more effectively with a function.
I would use a variable for this:
myFunction(){
zappo="echo"
$zappo "foo bar"
}
Or even a wrapper function:
zappo() {
|
How do you set the 16 Terminal Colors for Git-Bash? |
Console colors are stored in the registry under HKCU/Console/[window
name]/ColorTable00-15.
[window name] is either "Git Bash" for the start menu entry or something
like "C:_Program Files (x86)_Git_git-cheetah_.._bin_sh.exe" for the Windows
Explorer context menu entry (supplied by Git-Cheetah).
Alternatively, the registry settings can be overridden by storing an
NT_CONSOLE_PROPS structure with appropriate ColorTable settings in the "Git
Bash.lnk" shortcut via IShellLinkDataList::AddDataBlock. This happens e.g.
if you edit the properties of a console window started via shortcut, or if
you edit the shortcut properties directly.
If you want the values from the registry instead, create a new "Git
Bash.lnk" shortcut from scratch and leave the Options/Font/Layout/Colors
tabs alone.
|
bash: propagating exit code of command executed in alias |
It's better that you just use functions over aliases:
cda() {
cd /a
exit_code=$?
echo "STATUS: $exit_code"
return "$exit_code" # optional
}
cdb() {
cd /b
exit_code=$?
echo "STATUS: $exit_code"
return "$exit_code" # optional
}
As for the alias you could try adding a test in the end:
alias cda='cd /a; exit_code=$?; echo "STATUS: $exit_code"; [[ exit_code -eq
0 ]]'; alias cdb='cd /b'
|
Bash non scrolling terminal output |
Instead of printing whole lines (as with println or printing %n), write
backspace characters () or bare carriage returns without linefeeds (
) to
move the cursor back in front of what you want to print over.
|
git alias with bash conditional logic comparing strings - syntax issues |
You could try either the character code of the character you want, or the
hex name of the character you want. Here is a link to these things:
http://www.utf8-chartable.de/
At the core of what you are doing, you are just writing a bash script in
your environment. So whatever lets you write quotes outside of git's bash
interface should be able to work here.
|
MacOS dot file delete for MS-DOS devices |
Here is my clumsy answer to the Question posted above. The main drawbacks
are lack of much error handling or commenting, and the complexity level for
non-technical users who need to learn about making shell scripts
executable. If it could all be done in an AppleScript, it might be much
more useful for a wide range of users baffled by the dotfile problem.
Here's the Readme.txt file I've shared with the two scripts below:
noMacOSdots.app
-Introduction-
Sometimes you may want to share files with an MS-DOS or Microsoft Windows
user, or a non-Apple product such as a TV or media player. The problem is
that all disk devices including USB sticks that have been attached to a
MacOS computer or other Apple device will have files placed on them by
MacOS that are invisible to MacOS u
|
relation between init and bash terminal process |
Nothing is shared between init and its terminal children, nor between the
first terminal and its terminal child.
This is because, although fork() will make both processes (father and
child) to share some objects, exec() family functions completely replaces
the current process image with a new process image.
This means that all references to previous objects, such as shared file
descriptors from the father, are forgotten.
|
Multiple tab-completion routines in Bash terminal |
The keybindings themselves are part of readline, and can be changed in your
~/.inputrc or use the bind command in your .bashrc (etc.), but they don't
bind directly to user-defined functions, only indirectly as macros that
might call those functions.
"C-xhf": dump-functions # for ~/.inputrc
bind '"C-xhf":dump-functions' # in .bashrc (etc.)
bind -l will show you builtin functions you can bind to. You can add
macros this way, which let's you run any bash function you want, although
not in completion context, so the results don't get stuffed back into the
command line. Example:
"C-xc": "echo hi
" # note it's a just macro, not a direct binding.
I'm guessing you already know you can override completion with the complete
builtin for commands at the left on the command line.
|
stop bash script from outputting in terminal |
Append >> /path/to/outputfile/outputfile.txt to the end of every echo
statement
echo "Process is running." >> /path/to/outputfile/outputfile.txt
Alternatively, send the output to the file when you run the script from the
shell
[~]# sh check.sh >> /path/to/outputfile/outputfile.txt
|
New tab in Terminal.app does not open in same directory/bash fails (Mountain Lion) |
I had this problem too, and discovered that I had accidentally changed a
setting in the "Startup" tab of the Terminal preferences. The setting was
"Shells open with: Command (complete path): ."
I changed it back to "Shells open with: Default login shell" and that
solved the problem.
|
sentence as user input - multiple times from terminal - bash script |
This is because in your second call to read, you are using the -a argument
which does:
The words are assigned to sequential indices of the array variable aname,
starting at 0. aname is unset before any new values are assigned. Other
name arguments are ignored.
That appears to be not what you want.
|
`-bash: rbenv: command not found` comes up every time I open a terminal window. How do I fix this? |
Without being able to see your .bashrc or .bash_profile files, I would
guess that you have a line in one of them what is supposed to be loading
something from rbenv.
I would check there to see if there is something that might be loading is.
|
How to print out error messages into terminal screen while doing pipes (linux bash) |
Error messages written to standard error will not be sent to the piped
command. I mean if your command is:
cmd | cmd2
then only the stdout messages from cmd will be piped to cmd2 and not stderr
messages.
Here is an example I used. I tried cating a non-existing file and tried
greping some text:
$ cat non-existing-file.txt | grep something > grepped-text.txt
cat: non-existing-file.txt: No such file or directory
|
log4net rolling file appender (by date) overwriting existing file |
It looks like my theory was correct! The default file size is 10mb, and the
default rolling style is composite. Combined with the non static file name,
when it reached 10mb, it just rolled over to the same file and began
logging again.
|
Overwriting core data file then load new file |
Try in your handleOpenURL method to set the managedObjectContext,
managedObjectModel and persistentStoreCoordinator to nil. That should force
the app to reload the db file the next time CoreData is used to access
data.
|
Overwriting a file without the risk of a corrupt file |
You should lock the actual data file while you write its substitute, if
there's a chance that a different process could be going through the same
protocol that you are describing.
You can use flock for the file lock.
As for your temp file name, you could make your process ID part of it, for
instance "example.dat.3124," No other simultaneously-running process
would generate the same name.
|
Overwriting a line in CSV file with C++ |
There are no C++ functionality to "insert" or "remove" text in a text-file.
The only way to do that is to read the existing text in, and write out the
modified text.
If the new text fits in the same space as the old one, all you need to do
is to overwrite the existing text - and of course, you can always add extra
spaces before/after a comma in a .CSV file, without it becoming part of the
"field". But if the new data is longer, it definitely won't work to
"overwrite in place".
Adding to the end is relatively easy by using the ios_base::ate modifier.
But inserting in middle still involves basically reading until you find the
relevant place, and then, if the new text is longer, you have to read all
the following lines before you can write the new one(s) out.
|
Overwriting and Saving File using I/O and Datagridview |
On load, store the filename.
On save, if a filename has been stored, use that one instead (and then
reset it to null).
string currentFile = null;
...
currentFile = openFileDialog1.FileName;
...
if (currentFile != null) {
fn = currentFile;
currentFile = null;
}
|
PHP losing anything between PHP tags when overwriting file |
When you try and grab a php file from a remote server the file is parsed by
the server meaning it actually runs the PHP. You can't remotely get the
php contents of a file unless you FTP in or you set up the remote server to
not parse PHP (which I'm sure you don't want to do)
|
execute user inputed Windows (or bash) commands from batch (or bash) file? |
Do you need a full bash prompt?
Or would something like this be enough?
#!/bin/bash
echo -n "Enter cmd: "
read COMMAND
echo ${COMMAND} | bash
Also, in a script, you can just execute bash and get a full prompt in the
current environment.
|
Java overwriting an existing output file |
I would like to overwrite the file if I run the program again.
Pass false as 2nd argument, to set append to false:
FileOutputStream output = new FileOutputStream("output", false);
Check out the constructor documentation:
If the second argument is true, then bytes will be written to the end of
the file rather than the beginning.
|
Write in a text file without overwriting in fs node js |
Check the flags here:
http://nodejs.org/api/fs.html#fs_fs_open_path_flags_mode_callback - you are
currently using w+ which:
'w+' - Open file for reading and writing. The file is created (if it does
not exist) or truncated (if it exists).
You should use a instead:
'a' - Open file for appending. The file is created if it does not exist.
'ax' - Like 'a' but opens the file in exclusive mode.
'a+' - Open file for reading and appending. The file is created if it
does not exist.
'ax+' - Like 'a+' but opens the file in exclusive mode.
|
Buffered Writer overwriting file when not wanted |
You need to use append mode
new BufferedWriter(new FileWriter(yourFileName, true));
here, true means that the txt should be appended at the end of file.
Check the FileWriter javadoc for more information.
|
Overwriting a few lines in a file only if specific criteria are met |
Not sure if I understood your question correcly, but as I understand you
have to do the following:
Keep every line of inp2 file in the list of strings. Search for lines which
are starting with "recev:" in inp1 file. Every time if the condition "if
len(lines) == 5" is satisfied for line which contains "recev:", replace
that line with the first element of the kept list. Remove first element of
the list every time when "recev:" containing line is found in inp1 file.
|
node.js fs.writeFile Not Completely Overwriting File |
I've just tested this on 0.8.21 ( linux ) and this works as expected.
var fs = require('fs')
var str1 = "aaaaaaaaaa"
var str2 = "bbbbbb"
var str3 = "bbbbbbaaaa"
fs.writeFile('test',str1,function(){
fs.writeFile('test',str2,function(){
fs.readFile('test','utf8',function(err,buff){
console.log(buff === str2)
console.log(buff === str3)
})
})
})
output
> node test.js
true
false
|
I have an issue with fwrite not properly overwriting a file |
Use fflush()
http://php.net/manual/en/function.fflush.php
This function forces a write of all buffered output to the resource pointed
to by the file handle.
|
Using pickle to log user's input without overwriting the file |
You may want to check out Python's shelve module.
A “shelf” is a persistent, dictionary-like object. The difference
with “dbm” databases is that the values (not the keys!) in a
shelf can be essentially arbitrary Python objects — anything that the
pickle module can handle. This includes most class instances, recursive
data types, and objects containing lots of shared sub-objects. The keys are
ordinary strings.
Straight from the Docs:
import shelve
d = shelve.open(filename) # open -- file may get suffix added by low-level
# library
d[key] = data # store data at key (overwrites old data if
# using an existing key)
data = d[key] # retrieve a COPY of data at key (raise KeyError if no
# such key)
del d[key]
|
How to add a line in a text file without overwriting it (JAVA)? |
Use MODE_APPEND:
FileOutputStream output =
openFileOutput("latlngpoints.txt",Context.MODE_APPEND);
From the doc:
File creation mode: for use with openFileOutput(String, int), if the
file already exists then write data to the end of the existing file
instead of erasing it.
|
How to write more into a file without overwriting on pre-saved data |
First, you are calling createNewFile(). This indicates that you want to
create a new file. If you do not want to create a new file, do not call
createNewFile(). And, since the documentation for createNewFile() says
"This method is not generally useful", you may wish to consider just
getting rid of it.
Second, you need to indicate that you want to append to the existing data
when you open and use that file. The standard recipe for this:
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new
FileWriter("outfilename", true)));
out.println("the text");
out.close();
} catch (IOException e) {
//oh noes!
}
The true in the second parameter to the FileWriter constructor indicates
that you want to append instead of overwrite.
Third, do not hardcode paths in Android. /sdc
|
Injecting queries into DAOs via a spring config file |
If the purpose is to facilitate SQL modification without code
recompilation, then yes this will do. You just need to inject RuleDao into
your DAO classes.
However in my opinion SQL query modification should go through standard
software lifecycle (design, implement, test, operate). So I'm happy with my
SQL queries being hardcoded into DAO classes.
|
Running a .py script from bash, how can I pass a python variable back to the terminal once the .py is done running? |
You can write your variable and its value into an ini file from the python
script.
In Values.ini file
my_var="value"
After executing python script, just invoke Values.ini using . operator
. Values.ini
Now your shell variable $my_var will be having the assigned value.
The advantage with this method is that you can assign any number of
variables like this.
var1="value1"
var2="value2"
var3="value3"
|
bash script to write content into file. File content requires bash variables. How to do that? |
You're actually deliberately turning off parameter subsitution by enclosing
'ENDFILECONTENT' in quotes. See this excerpt from example 19-7 of the
advanced Bash scripting guide on Heredocs, slightly reformatted:
# No parameter substitution when the "limit string" is quoted or escaped.
# Either of the following at the head of the here document would have
# the same effect.
#
# cat <<"Endofmessage"
# cat <<Endofmessage
Remove the single quotes around 'ENDFILECONTENT' and BASH will replace the
variables as expected.
|