Termux 实用调整
什么是 termux?
对于那些不知道 termux 是什么的人:
Termux 是一款 Android 终端模拟器和 Linux 环境应用,无需 root 权限或设置即可直接运行。系统会自动安装精简的基础系统,其他软件包则可通过 APT 软件包管理器获取。
基本快捷键
Volume Down --> Ctrl
Volume Up --> Esc
Volume Up + 3 --> F3
因此,要清理屏幕,您可以按 ,Volume Down + l
就像在普通的 Linux 终端中一样
要退出终端,您可以按Volume Down + d
更多高级键盘设置(终端)请访问termux wiki 上的此链接。
使用F-droid代替 Google Play 商店
更新的 termux 版本只能在 F-droid repo 上找到,请在此处阅读更多信息
就我而言,我很难将 F-droid 直接下载到我的 Android 设备上,因此我将它下载到我的电脑上,然后使用 python 启动一个 http 服务器,以便直接在手机上下载它:
aria2c -c https://f-droid.org/F-Droid.apk
python3 -m http.server
我必须获取我的本地 IP(计算机)并在手机上的 Firefox 中输入它:
http://ip:8000
还有另一家替代商店:https://auroraoss.com/
环境变量
Termux 有一个$PREFIX
环境变量:
/data/data/com.termux/files/usr
在某些情况下,您可以使用它来避免输入上述所有路径
初始安装:
首次从 F-droid 安装:
termux termux-api
备份 termux 设置
来源:https ://wiki.termux.com/wiki/Backing_up_Termux
在此示例中,将显示 home 目录和 sysroot 目录的备份。生成的存档将存储在您的共享存储空间 (/sdcard) 上,并使用 gzip 进行压缩。
- 确保已授予存储权限:
termux-setup-storage
注意:每次遇到任何权限问题时,请撤销 termux 权限并运行termux-setup-storare
- 备份文件:
tar -zcf /sdcard/termux-backup.tar.gz -C /data/data/com.termux/files ./home ./usr
备份应该顺利完成,不会出现任何错误。除非用户滥用 root 权限,否则不应该出现任何权限拒绝。如果您收到一些关于套接字文件的警告,请忽略它们。
恢复
这里假设您已将主目录和用户目录备份到同一个存档中。请注意,此过程将覆盖所有文件。
- 确保已授予存储权限:
termux-setup-storage
- 提取 home 目录和 usr 目录并覆盖所有内容。使用 --recursive-unlink 选项删除所有垃圾文件和孤立文件。使用 --preserve-permissions 选项设置文件权限,与存档文件相同,并忽略 umask 值。通过组合这些额外选项,您将获得与存档文件完全相同的安装状态。
tar -zxf /sdcard/termux-backup.tar.gz -C /data/data/com.termux/files --recursive-unlink --preserve-permissions
现在使用通知中的“退出”按钮关闭 Termux,然后再次打开它。
使用termux-backup进行备份:
就我而言,我使用了这个命令
termux-backup ~/storage/shared/Documents/termux-backup.tar.xz
要恢复,只需将“备份”更改为“恢复”
修复:存储库正在维护或关闭
该解决方案来自此YouTube 视频/频道
错误如下:
N:无法验证元数据完整性,存储库现已禁用。N
:可能原因:存储库正在维护或关闭(sources.list URL 错误?)。
此问题是由于错误的仓库源或镜像导致的,因此软件包安装失败,并显示“仓库正在维护或关闭”的错误。
此问题的解决方案是使用命令更改镜像termux-change-repo
,本视频将对此进行讲解。
因此,命令是:
termux-change-repo
使用空格选择上述所有选项,直到到达下一个屏幕,如下所示:
就我而言,我选择了以下列表中的第二个
安装一些有用的应用程序
pkg update && pkg upgrade
pkg install termux-tools openssh mpv wget termux-api neovim python iproute2 git
提示:您可以缩写“install”,只需输入“in”
将您的公共 ssh 密钥复制到您的计算机
在你的 Android 上生成 ssh-key:
ssh-keygen -b 4096 -t rsa
ssh-copy-id -i ~/.ssh/id_rsa.pub user@ip
提示:生成 ssh 密钥时不要输入任何密码,并将 sshd 设置为仅允许公钥登录,这样您就可以轻松登录。
您还需要设置一个密码,以防您需要在没有密钥的情况下访问您的 ssh 服务器:
passwd
发现您的 termux“用户”名称:
whoami
--> this is mine: u0_a225
您还可以通过输入以下内容获取您的用户名:
echo $USER
启动你的 sshd:
sshd -p 2222
将您计算机的 ssh 公钥复制到您的 android(termux):
ssh-copy-id -p 2222 -i ~/.ssh/id_rsa.pub u_0a225@yourip
使用 scp
scp -P 2223 aliases u0_a103@192.168.15.30:~/storage/downloads
scp -P 8022 *.mp3 u0_184@192.168.15.2:~/storage/music
使用 nautilus 访问您的 termux
请记住相应地更改端口号!
sftp://u0_a225@phone/data/data/com.termux/files/home
sftp://u0_a225@192.168.0.100:8022/data/data/com.termux/files/home
一些有用的别名(~/.bashrc)
alias localip='ip addr | grep -Po '\''(?<=inet)\s(?!127)[^/]+'\'
alias vim='/data/data/com.termux/files/usr/bin/nvim'
设置文件夹
根据termux wiki 的说明:为了访问共享存储(/sdcard 或 /storage/emulated/0),Termux 需要存储访问权限。默认情况下不授予该权限,并且应用程序启动时也不会请求该权限,因为这对于应用程序的正常运行并非必需。
存储访问权限将不会启用对外部 SD 卡和通过 USB 连接的驱动器的写访问。
termux-setup-storage
termux 风格
对我来说,拥有一个美观的终端是至关重要的,因此:
git clone https://github.com/adi1090x/termux-style
cd termux-style
ls
chmod +x install
./install
termux-style
如何使用 Termux 下载 YouTube 视频
wget -c https://pastebin.com/raw/RijZvset -O install.sh
dos2unix install
chmod u+x install.sh
./install.sh
以更合理的方式设置你的 python 库:
pip3 install pipx
pipx ensurepath # make sure to set path
pipx install yt-dlp # fix some youtube-dl issues [official site](https://github.com/yt-dlp/yt-dlp)
pipx install yturl
然后您可以:
alias youtube-dl="/data/data/com.termux/files/home/.local/bin/yt-dlp"
安装脚本:
#!/data/data/com.termux/files/usr/bin/bash
# 4/05/2017 Gabi Tiplea
echo -e "Updating default packages\n"
apt update && apt -y upgrade
echo -e "Requesting acces to storage\n"
termux-setup-storage
sleep 5
echo -e "Installing python\n"
packages install -y python
echo -e "Installing youtube-dl\n"
yes | pip install youtube-dl
echo -e "Creating the Youtube folder to download the files\n"
mkdir ~/storage/shared/Youtube
echo -e "Creating youtube-dl folder for config\n"
mkdir -p ~/.config/youtube-dl
echo -e "Creating bin folder\n"
mkdir ~/bin
echo -e "Downloading and installing termux-url-opener\n"
wget http://pastebin.com/raw/LhDxGbtY -O ~/bin/termux-url-opener
dos2unix ~/bin/termux-url-opener
echo -e "\n"
echo -e "Copyright 2017 Gabi Tiplea\n"
安装trash-cli
pipx install trash-cli
alias rm='echo use trash instead!'
Trash-cli 将您的文件移动到~/.local/share/Trash
设置 youtube-dl 脚本权限
Fasd_cd
Fasd(发音类似于“fast”)是一款命令行效率提升工具。Fasd 为 POSIX shell 提供快速访问文件和目录的功能。它的灵感源自 autojump、z 和 v 等工具。Fasd 会跟踪您访问过的文件和目录,以便您在命令行中快速引用它们。
fasd 这个名字来自默认建议的别名 f(文件)、a(文件/目录)、s(显示/搜索/选择)、d(目录)。
Fasd 根据“频率”(即同时考虑“频率”和“新近度”)对文件和目录进行排序。“频率”一词最初由 Mozilla 提出,并应用于 Firefox(链接)。
########### aliases para o fasd_cd ##########
# aliases para fasd
alias a='fasd -a' # any
alias s='fasd -si' # show / search / select
alias d='fasd -d' # directory
alias f='fasd -f' # file
alias vf='vim $(fasd -f)'
alias sd='fasd -sid' # interactive directory selection
alias sf='fasd -sif' # interactive file selection
alias z='fasd_cd -d' # cd, same functionality as j in autojump
alias zz='fasd_cd -d -i' # cd with interactive selection
alias v='f -e nvim' # open file with vim
#alias v='f -t -e vim -b viminfo'
alias _!='fc -e "sed -i -e \"s/^/sudo /\""' # sudo last command
还要将这些行添加到你的 .bashrc
# init configuration of fasd tool ##############
# source: https://github.com/clvv/fasd
eval "$(fasd --init auto)"
fasd_cache="$HOME/.fasd-init-bash"
if [ "$(command -v fasd)" -nt "$fasd_cache" -o ! -s "$fasd_cache" ]; then
fasd --init posix-alias bash-hook bash-ccomp bash-ccomp-install >| "$fasd_cache"
fi
更好的 bash 补全
# ------------------------------------------------------
# FILE ~/.inputrc
# CREATED Qui 13/Out/2011 hs 09:39
# LAST CHANGE 2013 Jul 17 14:41:08
# SITE http://vivaotux.blogspot.com
# TWITTER http://www.twitter.com/voyeg3r
# EMAIL <voyeg3r gmail.com>
# DOWNLOAD https://gist.github.com/1284081
#
# key bindings for bash
#
# ( O O )
# --------------oOO--(_)--OOo---------------------------
# download
# wget -c https://bitbucket.org/sergio/dotfaster/raw/master/inputrc -O ~/.inputrc
#-------------------------------------------------------
# Use `bind -v` to see current settings
#-------------------------------------------------------
# definir no ~/ .bashrc o local do inputrc
# INPUTRC=~/.inputrc
# Referências
# https://bugs.launchpad.net/ubuntu/+source/base-files/+bug/103986
# http://superuser.com/questions/222390/making-bash-tab-completion-more-like-cmd-exe
# http://brettterpstra.com/2011/09/25/quick-tip-some-inputrc-fun/
# pesquisar sobre as opções 'shopt' do bash
# pesquisar as opções 'cmdhist' 'nocaseglob' 'nocasematch'
# By default, C-x C-r is bound to re-read-init-file.
# start-kbd-macro - C-x (
# Begin saving the characters typed into the current keyboard macro.
# end-kbd-macro - C-x )
# Stop saving the characters typed into the current keyboard macro and store the definition.
# call-last-kbd-macro - C-x e
# Adding this to your /etc/inputrc or ~/.inputrc will result in a character
# # being appended to any file-names returned by completion, in much the same
# # way as ls -F works.
set visible-stats on
set blink-matching-paren on
set bell-style visible
set convert-meta off
set input-meta on
set output-meta on
set show-mode-in-prompt on
# https://unix.stackexchange.com/questions/112406/how-do-i-switch-to-vi-editing-mode-in-readline
set vi-ins-mode-string (ins)\1\e[5 q\2
set vi-cmd-mode-string (cmd)\1\e[1 q\2
## to change to vi mode: set -o vi | set -o emacs
# Be more intelligent when autocompleting by also looking at the text after
# the cursor. For example, when the current line is "cd ~/src/mozil", and
# the cursor is on the "z", pressing Tab will not autocomplete it to "cd
# ~/src/mozillail", but to "cd ~/src/mozilla". (This is supported by the
# Readline used by Bash 4.)
set skip-completed-text on
$if Bash
# Search history back and forward using page-up and page-down
"\e[5~": history-search-backward
"\e[6~": history-search-forward
# Cycle through ambiguous completions instead of list (option bellow)
"\C-i": menu-complete
# Binding Shift-Tab to go backward is a little tricker:
"\e[Z": "\e-1\C-i"
# control-x-p to edit path
"\C-xp": "PATH=${PATH}\e\C-e\C-a\ef\C-f"
# prepare to type a quoted word -- insert open and close double quotes
# and move to just after the open quote
"\C-x\"": "\"\"\C-b"
"\C-x'": "''\C-b"
# insert option macro (if you forgot option in previous cmd type Alt-o)
"\eo": "\C-p\C-a\ef "
# show help for a commad with alt-h
"\eh": "\C-a\eb\ed\C-y\e#man \C-y\C-m\C-p\C-p\C-a\C-d\C-e"
# Completion
set match-hidden-files off
set completion-query-items 350
set completion-ignore-case on
set show-all-if-ambiguous on
set show-all-if-unmodified on
set page-completions off
set visible-stats on
set completion-map-case on
# do history expansion when space entered
#Space: magic-space
$endif
$include /etc/inputrc
$if exists("&wildignorecase")
set wildignorecase
$endif
# put in your ~/.bashrc
# complete -d cd mkdir rmdir
Bash 提示符
我发现了一个很棒的项目,它可以给你一个很棒的 bash 提示符:
https://github.com/1Tech-X/termux-PS1
Bashrc 文件“~/.bashrc”
# Last Change: Thu, 20 Jan 2022 14:22
# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples
# http://www.caliban.org/bash/
# ( O O )
# +===========oOO==(_)==OOo==============+
# | |
# | °v° Sergio Luiz Araujo Silva |
# | /(_)\ Linux User #423493 |
# | ^ ^ voyeg3r gmail.com |
# +======================================+
#
# References: https://github.com/fnichol/bashrc/blob/master/bashrc
INPUTRC=~/.inputrc
EDITOR='/data/data/com.termux/files/usr/bin/nvim'
# avoid ctrl-s freeze your terminal
stty stop ""
# protegendo arquivos contra sobrescrita
#set -o noclobber
# bash completion to sudo command
complete -cf sudo
complete -cf man
complete -cf gksu
complete -d cd mkdir rmdir
# autocomplete ssh commands
complete -W "$(echo `cat ~/.bash_history | egrep '^ssh ' | sort | uniq | sed 's/^ssh //'`;)" ssh
complete -A file -X '!*.@(Z|gz|tgz)' gunzip
[ -f ~/.vim/git-completion.bash ] && source ~/.vim/git-completion.bash
function gm() {
git commit -am "$1" && git push
}
function vif() {
local fname
cd ~/.dotfiles
fname=$(fzf) || return
vim "$fname"
}
[ -f ~/.bash_aliases ] && . ~/.bash_aliases
htmldecode() { : "${*//+/ }"; echo -e "${_//&#x/\x}" | tr -d ';'; }
urldecode() { : "${*//+/ }"; echo -e "${_//%/\\x}"; }
alias='$EDITOR ~/.bashrc ; source ~/.bashrc'
alias allcomm='whatis `compgen -c` | less' # list all possible commands
alias x='extract'
alias pbcopy='xclip -selection clipboard'
alias pbpaste='xclip -selection clipboard -o'
alias proz='proz -v -f -s'
alias xclip='xclip -selection c'
alias config-date='sudo ntpdate -u -b bonehed.lcs.mit.edu'
alias aria2c='aria2c -x5 -c'
alias 4shared='cadaver http://webdav.4shared.com/'
alias compilalivro='make clean; make && make show'
#alias updatelivro='hg push ssh://hg@bitbucket.org/sergio/learn-english'
alias less='less -r'
alias ls="ls --color=auto"
alias dir="dir --color=auto"
alias lsd="ls -d */"
alias grep="grep --color=auto"
alias dmesg='dmesg --color'
#alias rm='mv -t ~/.local/share/Trash/files'
alias syncode='cd ~/.vim && git push -u origin master'
alias ssh="ssh -C"
alias scp='scp -r '
alias gril="grep -ril"
alias youtube-dl="youtube-dl -t"
alias xterm='/usr/bin/xterm -ls -bg black -fg white -cr -fs 11 white -hc white rightbar'
alias ll='ls -l'
alias la='ls -A'
alias l='ls -CF'
alias lvim='/data/data/com.termux/files/usr/bin/nvim -c "normal '\''0"'
alias cdesk="cd ${HOME}/Desktop"
alias iso2utf='iconv -f iso-8859-1 -t utf-8'
alias utf2iso='iconv -f utf-8 -t iso-8859-1'
alias path='echo -e ${PATH//:/\\n}'
alias vim='/data/data/com.termux/files/usr/bin/nvim'
command -v apt-proz >/dev/null && INSTALLER="apt-proz" || INSTALLER="apt-get"
#alias update='sudo apt-proz update'
alias upgrade='sudo apt-proz update && sudo apt-proz upgrade'
alias acs='apt-cache search'
alias install='sudo apt-proz -y install'
# Listen to Air Traffic Control, used to be scripts.
alias GIG='mplayer http://rio.radioetvweb.com.br:8246'
alias GRU='mplayer http://rio.radioetvweb.com.br:8298'
alias POA='mplayer http://rio.radioetvweb.com.br:8282'
alias CGH='mplayer http://rio.radioetvweb.com.br:8300'
alias classic='mplayer http://80.237.154.83:8120'
# watch aljazeera
alias alj='rtmpdump -v -r "rtmp://aljazeeraflashlivefs.fplive.net/aljazeeraflashlive-live/aljazeera_eng_med" | mplayer -'
shopt -s histverify # verifica comandos do histórico
shopt -s checkwinsize # ajusta janela redimensionada
shopt -s hostcomplete
shopt -s extglob
[ ${BASH_VERSINFO[0]} -ge 4 ] && shopt -s globstar
shopt -s cdspell # fix wrong type keys
shopt -s dirspell
shopt -s autocd
# convert text to lowcase
lower() { echo "${@}" | awk '{print tolower($0)}' ;}
upper() { echo "${@}" | awk '{print toupper($0)}' ;}
expandurl() { curl -sIL $1 | awk '/^Location/ || /^Localização/ {print $2}' ; }
calc(){ echo "scale=2;$@" | bc;}
ff () { find . -type f -iname '*'"$@"'*' ; }
mkcd() { mkdir -p "$@" && cd $_; }
gsend() { git commit -am "$1" && git push ;}
gst() { git status;}
decToBin () { echo "ibase=10; obase=2; $1" | bc; }
decTohex () { bc <<< "obase=16; $1"; }
biggest (){ du -k * | sort -nr | cut -f2 | head -20 | xargs -d "\n" du -sh; }
top10 () { history | awk '{print $2}' | sort | uniq -c | sort -rn | head ; }
beep () { echo -e -n \\a ; }
dict() { curl "dict://dict.org/d:${1%%/}";}
# If not running interactively, don't do anything
[ -z "$PS1" ] && return
# trying to fix sound in gnash flash
export SDL_AUDIODRIVER=alsa
export AUDIODEV=plug:dmix
# don't put duplicate lines in the history. See bash(1) for more options
export HISTCONTROL=ignoredups
# ... and ignore same sucessive entries.
export HISTCONTROL=ignoreboth
export HISTIGNORE="&:ls:pwd:[bf]g:ssh *:exit"
export LS_COLORS=$LS_COLORS:"*.wmv=01;35":"*.wma=01;35":"*.flv=01;35":"*.m4a=01;35":"*.mp3=01;35":"*.mp4=01;35"
function add_ls_colors { export LS_COLORS="$LS_COLORS:$1"; }
#export LS_COLORS=
add_ls_colors "*.ps=00;35:*.eps=00;35:*.pdf=00;35:*.svg=00;35"
add_ls_colors "*.jpg=00;35:*.png=00;35:*.gif=00;35"
add_ls_colors "*.bmp=00;35:*.ppm=00;35:*.tga=00;35"
add_ls_colors "*.xbm=00;35:*.xpm=00;35:*.tif=00;35"
add_ls_colors "*.png=00;35:*.mpg=00;35:*.avi=00;35"
## Archive files
add_ls_colors "*.tar=00;31:*.tgz=00;31:*.arj=00;31"
add_ls_colors "*.taz=00;31:*.lzh=00;31:*.zip=00;31"
add_ls_colors "*.z=00;31:*.Z=00;31:*.gz=00;31"
add_ls_colors "*.bz2=00;31:*.deb=00;31:*.rpm=00;31"
## Fixes
add_ls_colors "*.com=00;00:"
# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "$debian_chroot" ] && [ -r /etc/debian_chroot ]; then
debian_chroot=$(cat /etc/debian_chroot)
fi
if [[ "$(id -un)" != "root" ]]; then
PS1='`[ $? = 0 ] && echo "\[\033[01;34m\]✔\[\033[00m\]"\
|| echo "\[\033[01;31m\]✘\[\033[00m\]"` [\A] \[\033[01;32m\]\u:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
# prompt para o root
#PS1='\[\033[01;31m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
PS1='`[ $? = 0 ] && echo "\[\033[01;34m\]✔\[\033[00m\]" ||\
echo "\[\033[01;31m\]✘\[\033[00m\]"` [\A] \[\033[01;31m\]\u\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
fi
export prompt_command='echo -ne "\033]0;"`hostname -i`"\007"'
getextension () {
echo "Full filename: $(basename ${1})"
echo "Extension: ${1##*.}"
echo "without extension: ${1%.*}"
}
getaudio () {
# dependences: libmp3lame-dev libmad0-dev and compile sox
# http://michalfapso.blogspot.com.br/2012/01/using-google-text-to-speech.html
var="${@}"
echo "${@}" > teste.txt
filename="${var// /_}.mp3"
speak.pl en teste.txt "$filename"
rm -rf "$filename".tmp && rm -f teste.txt
echo "[sound:${filename}]" | xclip -selection c
mpg123 "$filename"
}
eng2audio () {
# see this: https://gist.github.com/michalfapso/3110049/raw
# http://michalfapso.blogspot.com.br/2012/01/using-google-text-to-speech.html
# http://mostovenko.blogspot.com.br/2012/04/voicing-messages-in-python-or-fun-with.html
# versão no snipt: https://snipt.net/voyeg3r/
# how truncate string --> echo ${var:start:end}
# removendo o último caractere de uma variável ${var:0:-1}
# vou precisar truncar a string::::: echo "Sua string contém "${#var}" caracteres"
if ping -q -c2 www.google.com >/dev/null ; then
FILENAME="${@:?Usage: $0 give me some words to speech}"
FILENAME=`awk '{print tolower($0)}' <<< "$FILENAME"`
url="http://translate.google.com/translate_tts?ie=UTF-8&tl=en&q="
wget -q -U Mozilla -O "${FILENAME// /_}.mp3" "${url}${FILENAME// /+}+' '"
[ -f "${FILENAME// /_}.mp3" -a ! -s "${FILENAME// /_}.mp3" ] && { rm -f "${FILENAME// /_}.mp3" ; echo 'error!'; }
command -v mpg123 > /dev/null && mpg123 -q "${FILENAME// /_}.mp3"
echo "[sound:${FILENAME// /_}.mp3]" | xclip -selection c
fi
}
mp4tomp3 () {
# http://stackoverflow.com/questions/5365090/removing-extension-from-file-without-knowing-it
command -v ffmpeg > /dev/null || sudo apt-get install -y ffmpeg
command -v lame > /dev/null || sudo apt-get install -y gstreamer0.10-plugins-ugly
local var="${1%.*}" # strip extension
local newname="${var// /_}.mp3" # get rid space and add mp3 extension
ffmpeg -i "$1" -f mp3 -ab 320000 -vn "$newname"
}
youtube-mp3 () {
# put thins function in your ~/.bashrc
${1:?"error: I need a youtube link"}
# testing existence of programs
NEEDED_COMMANDS="youtube-dl ffmpeg"
missing_counter=0
for needed_command in $NEEDED_COMMANDS; do
if ! hash "$needed_command" >/dev/null 2>&1; then
printf "Command not found in PATH: %s\n" "$needed_command" >&2
((missing_counter++))
fi
done
if ((missing_counter > 0)); then
sudo apt-get install -y $NEEDED_COMMANDS
fi
# geting video and converting with ffmpeg
youtube-dl --restrict-filenames -x --audio-format=mp3 --audio-quality 320k "${1}"
}
geturls () {
# source: http://stackoverflow.com/questions/2804467/spider-a-website-and-return-urls-only
${1?"Usage: geturls Link"}
wget -q "$1" -O - | \
tr "\t\r\n'" ' "' | \
grep -i -o '<a[^>]\+href[ ]*=[ \t]*"\(ht\|f\)tps\?:[^"]\+"' | \
sed -e 's/^.*"\([^"]\+\)".*$/\1/g'
}
backup() {
file=${1:?"error: I need a file to backup"}
timestamp=$(date '+%Y-%m-%d-%H:%M:%S')
backupdir=~/backups
[ -d ${backupdir} ] || mkdir -p ${backupdir}
cp -a ${file} ${backupdir}/$(basename ${file}).${timestamp}
return $?
}
#diskusage() {
# du -ks "$@" | sort -nr | \
# awk '{ \
# if ($1 > 1048576) printf("%8.2fG", $1/1048576) ; \
# else if ($1 > 1024) printf("%8.2fM", $1/1024) ; \
# else printf("%8.2fK", $1) ; \
# sub($1, "") ; print \
# }'
#}
getmp3 (){
${1?"Usage: getmp3 Link"}
for i in "`wget -q "$1" -O - | grep -i -o 'http://.*\.mp3'`"; do
wget -c "$i"
done
}
compact() {
# source: http://jfmitre.com/2012/10/compactando-arquivos-no-terminal-do.html
# compact arquivo_compactado.EXTENSÃO lista de arquivos para compactar
if [ "$#" -ge "1" ]; then
case "$1" in
*.[tT][aA][rR].[bB][zZ]|*.[tT][bB][zZ])
local file="$1"; shift; tar jcvf "$file" "$@" ;;
*.[tT][aA][rR].[bB][zZ]2|*.[tT][bB][zZ]2)
local file="$1"; shift; tar jcvf "$file" "$@" ;;
*.[tT][aA][rR].[gG][zZ]|*.[tT][gG][zZ])
local file="$1"; shift; tar zcvf "$file" "$@" ;;
*.[gG][tT][gG][zZ])
local file="$1"; shift; tar zcvf "$file" "$@" ;;
*[bB][zZ]2)
shift; bzip2 -z -k "$@" ;;
*.[rR][aA][rR])
local file="$1"; shift; rar a -r "$file" "$@" ;;
*[gG][zZ])
shift; gzip -r "$@" ;;
*.[tT][aA][rR])
local file="$1"; shift; tar cvf "$file" "$@" ;;
*.[zZ][iI][pP])
local file="$1"; shift; zip -r "$file" "$@" ;;
*.7[zZ])
local file="$1"; shift; 7z a -r "$file" "$@" ;;
*.[xX][zZ])
local file="$1"; shift; tar Jcvf "$file" "$@" ;;
*) echo "don't know how to compact '$i' ..." ;;
esac
else
echo "Insufficient arguments."
fi ; }
extract() {
# agradeça esta função ao J.F.Mitre
# http://jfmitre.com/2010/11/descompactando-arquivos-no-terminal-do.html
for i in "$@"; do
if [ -f "$i" ]; then
case "$i" in
*.[tT][aA][rR].[bB][zZ]|*.[tT][bB][zZ]) tar xjvf "$i" ;;
*.[tT][aA][rR].[bB][zZ]2|*.[tT][bB][zZ]2) tar xjvf "$i" ;;
*.[tT][aA][rR].[gG][zZ]|*.[tT][gG][zZ]) tar xzvf "$i" ;;
*.[gG][tT][gG][zZ]) tar xzvf "$i" ;;
*.[bB][zZ]2) bunzip2 "$i" ;;
*.[rR][aA][rR]) rar x -o+ "$i" ;;
*.[gG][zZ]) gunzip "$i" ;;
*.[tT][aA][rR]) tar xvf "$i" ;;
*.[zZ][iI][pP]) unzip -o "$i" ;;
*.Z) uncompress "$i" ;;
*.7[zZ]) 7z x "$i" ;;
*) echo "don't know how to extract '$i' ..." ;;
esac
else
echo "$i is not a valid file"
fi
done
}
# enable programmable completion features (you don't need to enable
# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
# sources /etc/bash.bashrc).
if [ -f /etc/bash_completion ] && ! shopt -oq posix; then
. /etc/bash_completion
fi
# Evita histórico com linhas duplicadas
export HISTCONTROL=ignoredups
# configuração do path
if [ -d /usr/local/texlive/2013/bin/i386-linux ] ; then
PATH=/usr/local/texlive/2013/bin/i386-linux:$PATH
PATH=/usr/local/texlive/2013/texmf-dist/doc/man:$PATH
fi
[ -d $PREFIX/bin ] && PATH=$PREFIX/bin:$PATH
# para chamar o pythonrc
PYTHONSTARTUP="$HOME/.pythonstartup"
export PYTHONSTARTUP
shell () {
ps | grep `echo $$` | awk '{ print $4 }'
}
groove-dl-cli(){ python2.7 /usr/share/groove-dl/groove.py "$@" ;}
up () {
# Created at: 2012/06/19 10:37:26
# Go up directory tree X number of directories
# source: http://orangesplotch.com/bash-going-up/
# see explanation at link above, worth!
# I found this here: http://askubuntu.com/questions/110922/climb-up-the-directory-tree-faster
# put this function to your ~/.bashrc
# binding this function to key see below
# http://stackoverflow.com/questions/4200800/in-bash-how-do-i-bind-a-function-key-to-a-command
COUNTER="$@";
# default $COUNTER to 1 if it isn't already set
if [[ -z $COUNTER ]]; then
COUNTER=1
fi
# make sure $COUNTER is a number
if [ $COUNTER -eq $COUNTER 2> /dev/null ]; then
nwd=`pwd` # Set new working directory (nwd) to current directory
# Loop $nwd up directory tree one at a time
until [[ $COUNTER -lt 1 ]]; do
nwd=`dirname $nwd`
let COUNTER-=1
done
cd $nwd # change directories to the new working directory
else
# print usage and return error
echo "usage: up [NUMBER]"
return 1
fi
}
myip (){
clear
echo
DEV=`awk '/UG/ {print $NF}' <(/sbin/route -n)`
#DEV=`awk '/eth/ {print $1}' <(netstat -i)` # indentifica o device
IPLOCAL=`hostname -I`
MEUIP=`awk '/inet end/ {print $3}' <(/sbin/ifconfig $DEV)`
IPEXTERNO=`curl --connect-timeout 4 -s sputnick-area.net/ip`
echo " IP LOCAL: .....${IPLOCAL:-'off-line'}"
echo " NETMASK: ......`awk -F':' '/Mas/ {print $4}' <(/sbin/ifconfig $DEV)`"
echo " MAC ADDRESS: ..`awk '/HW/ {print $7}' <(/sbin/ifconfig $DEV)`"
echo " ROUTER: .......`awk '/UG/ {print $2}' <(/sbin/route -n)`"
echo " IP EXTERNO: ...${IPEXTERNO}"
echo
read -sn 1 -p " Pressione uma tecla para continuar..."
clear
}
_getdomainnameonly(){
local f="${1,,}"
# remove protocol part of hostname
f="${f#http://}"
f="${f#https://}"
f="${f#ftp://}"
f="${f#scp://}"
f="${f#scp://}"
f="${f#sftp://}"
# remove username and/or username:password part of hostname
f="${f#*:*@}"
f="${f#*@}"
# remove all /foo/xyz.html*
f=${f%%/*}
# show domain name only
echo "$f"
}
ping(){
local array=( "-n -c 4 -i 0.2 -W1" "$@" ) # get all args in an array
local len=${#array[@]} # find the length of an array
local host=${array[$len-1]} # get the last arg
local args=${array[@]:0:$len-1} # get all args before the last arg in $@ in an array
#local _ping="/bin/ping"
local c=$(_getdomainnameonly "$host")
[ "$t" != "$c" ] && echo "Sending ICMP ECHO_REQUEST to \"$c\"..."
# pass args and host
#$_ping $args $c # improving script
command ping $args $c
}
host(){
local array=( $@ )
local len=${#array[@]}
local host=${array[$len-1]}
local args=${array[@]:0:$len-1}
#local _host="/usr/bin/host"
local c=$(_getdomainnameonly "$host")
[ "$t" != "$c" ] && echo "Performing DNS lookups for \"$c\"..."
#$_host $args $c
command host $args $c
}
export LESS="-P ?c<- .?f%f:Standard input. ?n:?eEND:?p%pj\%.. .?c%ccol . ?mFile %i of %m .?xNext\ %x.%t Press h for help"
man() { # wrapper para o comando man
env \
LESS_TERMCAP_mb=$(printf "\e[1;31m") \
LESS_TERMCAP_md=$(printf "\e[1;31m") \
LESS_TERMCAP_me=$(printf "\e[0m") \
LESS_TERMCAP_se=$(printf "\e[0m") \
LESS_TERMCAP_so=$(printf "\e[1;44;33m") \
LESS_TERMCAP_ue=$(printf "\e[0m") \
LESS_TERMCAP_us=$(printf "\e[1;32m") \
man "$@"
}
apt-history () {
case "$1" in
install)
cat /var/log/dpkg.log | grep 'install '
;;
upgrade|remove)
cat /var/log/dpkg.log | grep $1
;;
rollback)
cat /var/log/dpkg.log | grep upgrade | \
grep "$2" -A10000000 | \
grep "$3" -B10000000 | \
awk '{print $4"="$5}'
;;
*)
cat /var/log/dpkg.log
;;
esac
}
# set o vim como editor padrão
export EDITOR=vim
export VISUAL=vim
CDPATH=.:..:~:~/docs/img:~/docs:~/bin:~/tmp
export PROMPT_COMMAND="history -a"
export HISTFILESIZE=2000
# desabilitando a biblioteca pango para o firefox
export MOZ_DISABLE_PANGO=1
# http://ubuntuforums.org/archive/index.php/t-80289.html
export FLASH_GTK_LIBRARY=libgtk-x11-2.0.so.0
if [ -d /var/lib/gems/1.8 ]; then
export PATH=/var/lib/gems/1.8/bin:$PATH
fi
# Instalacao das Funcoes ZZ (www.funcoeszz.net)
#export ZZOFF="" # desligue funcoes indesejadas
#export ZZPATH="/home/sergio/bin/funcoeszz" # script
#source "$ZZPATH"
# Instalacao das Funcoes ZZ (www.funcoeszz.net)
#source /usr/bin/funcoeszz
#export ZZPATH=/usr/bin/funcoeszz
if [ -d ~/anaconda ] ; then
# added by Anaconda 1.8.0 installer
# "source activate ~/anaconda"
# http://va.mu/dkRc
export PATH="/home/sergio/anaconda/bin:$PATH"
fi
# init configuration of fasd tool ##############
# source: https://github.com/clvv/fasd
eval "$(fasd --init auto)"
fasd_cache="$HOME/.fasd-init-bash"
if [ "$(command -v fasd)" -nt "$fasd_cache" -o ! -s "$fasd_cache" ]; then
fasd --init posix-alias bash-hook bash-ccomp bash-ccomp-install >| "$fasd_cache"
fi
source "$fasd_cache"
unset fasd_cache
# interactive fasd
alias zi="fasd -e cd -i"
alias a='fasd -a' # any
alias s='fasd -si' # show / search / select
alias d='fasd -d' # directory
alias f='fasd -f' # file
alias sd='fasd -sid' # interactive directory selection
alias sf='fasd -sif' # interactive file selection
alias z='fasd_cd -d' # cd, same functionality as j in autojump
alias zz='fasd_cd -d -i' # cd with interactive selection
#### end configuration of fasd tool ##############
#[ -f ~/.fzf.bash ] && source ~/.fzf.bash
#source ~/.shortcuts